views:

62

answers:

2

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?

+1  A: 

I guess you need more advance logic. Best to first locate all real tags using a regular expression like "(<[^>]+>)" and only replace text outside those matches, but obviously you won't be able to use a replaceAll method then. It will be more of a plumbing job...

Koen
+2  A: 

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.

Paul Clapham