Skip to content Skip to sidebar Skip to footer

Java Library To Escape/clean XML?

I get some malformed xml text input like: 'something 8 > 3, 2 < 3, ... something' I want to clean the input so to get: '

Solution 1:

JTidy is "HTML syntax checker and pretty printer. Like its non-Java cousin, JTidy can be used as a tool for cleaning up malformed and faulty HTML"

But it can also be used with xml. Check the documentation. It's incredible smart, it will probably work for you.


Solution 2:

I don't know of any library that would do that. Your input is malformed XML, and no proper XML parser would accept it. More important, it is not always possible to distinguish an actual tag from something that looks-like-a-tag-but-is-really-text. Therefore any heuristic-based attempt that you make to solve the problem will be fragile; i.e. it could occasionally produce malformed XML.

The best approach is address the problem before you assemble the XML.

  • If you generate the XML by (for example) unparsing a DOM, then the unparser will take care of the escaping for you.
  • If you are generating the XML by templating or string bashing, then you need to call something like StringEscapeUtils.escapeXml on the relevant text chunks ... before the XML tags get incorporated.

If you leave the problem until after the "XML" has been assembled, it cannot be properly fixed.


Solution 3:

The best solution is to fix the program generating your text input. The easiest such fix would involve an escape utility like the other answers suggested. If that's not an option, I'd use a regular expression like

</?[a-zA-Z]+ */?>

to match the expected tags, and then split the string up into tags (which you want to pass through unchanged) and text between tags (against which you want to apply an escape method.)

I wouldn't count on an XML parser to be able to do it for you because what you're dealing with isn't valid XML. It is possible for the existing lack of escaping to produce ambiguities, so you might not be able to do a perfect job either.


Solution 4:

Check out Guava's XmlEscaper. It is in pre-release for version 11 but the code is available.


Solution 5:

Apache Commons Lang contains a class named StringEscapeUtils which does exactly what you want! The method you'd want to use is escapeXml, I presume.


Post a Comment for "Java Library To Escape/clean XML?"