Reputation: 13
I'm using the following method to read in a line of text from an XML document via the web:
public static String getCharacterDataFromElement(Element e) {
Node child = ((Node) e).getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
It works fine, but if it comes across a character such as an ampersand which are not written like &
etc it will then completely ignore that character and the rest of the line. What can I do to rectify this?
Upvotes: 1
Views: 140
Reputation: 163322
I suspect the talk of the input not being well-formed is a red herring. If the source document contains entity references then an element may contain multiple text node children, and your code is only reading the first of them. It needs to read them all.
(I think there are easier ways of getting the text content of a Node in DOM. But I'm not sure, I never use the DOM if I can avoid it because it makes everything so difficult. You're much better off with JDOM or XOM.)
Upvotes: 0
Reputation: 38410
The only proper solution ist to correct the XML, so that the &
is written as &
, or the texts are wrapped in <![CDATA[
... ]]>
.
It's not actually XML unless you escape ampersands or use CDATA.
Upvotes: 3