Search code examples
javaxmlnon-well-formed

Replacing characters in a non well-formed XML body


In a (Java) code that I'm working on, I sometimes deal with a non well-formed XML (represented as a Java String), such as:

<root>
  <foo>
    bar & baz < quux
  </foo>
</root>

Since this XML will eventually need to be unmarshalled (using JAXB), obviously this XML as is will throw exception upon unmarshalling.

What's the best way to replace the & and the < to its character entities? For &, it's as easy as:

xml.replaceAll("&", "&amp;")

However, for the < symbol, it's a bit tricky since obviously I don't want to replace the < that's used for the XML tag opening 'bracket'.

Other than scanning the string and manually replacing < in the XML body with &lt;, what other option can you suggest?


Solution

  • Frankly, the best way to repair malformed XML is to send it back to whoever produced it and ask them to send you well-formed XML instead. You show a trivial example, which potentially could have a solution, but a general method for repairing malformed XML is going to be a horrendous job.

    And since XML parsers aren't required to handle malformed XML, your parser isn't required to either. Just don't do it.