开发者

CharacterData ignoring non escaped characters

开发者 https://www.devze.com 2023-03-13 15:02 出处:网络
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) {

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 an开发者_如何学Cd the rest of the line. What can I do to rectify this?


The only proper solution ist to correct the XML, so that the & is written as &amp;, or the texts are wrapped in <![CDATA[ ... ]]>.

It's not actually XML unless you escape ampersands or use CDATA.


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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号