0

我有一个带有 CDATA 的 XML。这是我试图加载到 Java DOM 中的 XML。

<?xml version="1.0" encoding="utf-8"?><search:Search xmlns:search="Search"><search:Response xmlns="Search"><search:Store xmlns="Search">";
<search:Result xmlns="Search">";
<search:Properties xmlns="Search">";
<email2:ConversationId xmlns:email2="Email2"><![CDATA["B3:5F:18:81:37:4B:E4:4C:97:CE:9A:5A:18:6E:DE:8D:"]]></email2:ConversationId>";
<email:Categories xmlns:email="Email"></email:Categories>
</search:Properties>
</search:Result>
</search:Store>
</search:Response>
 </search:Search>

这是加载它的代码:

import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSParser;
...
...
    try {
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl = (DOMImplementationLS)registry.getDOMImplementation("LS");
        LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
        DOMInputImpl input = new DOMInputImpl();
        input.setByteStream(new ByteArrayInputStream(xmlString.getBytes("utf-8")));
        xmlDoc = builder.parse(input);
        return xmlDoc;
    } catch (ClassNotFoundException | InstantiationException
            | IllegalAccessException | ClassCastException | UnsupportedEncodingException e) {
        throw new MyException(e);
    }

但是,我发现解析后的文档没有 CDATA NodeType org.w3c.dom.CDATASection。相反,nodetype 以#text 的形式出现。

任何帮助将非常感激。

4

1 回答 1

0

Interesting! LSParser "converts" CDATA section nodes to text nodes (probably stated somewhere in the spec). However if you use the JAXP API (which is a lot less noisy) you'll get #cdata-section

    DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
    f.setNamespaceAware(true);
    DocumentBuilder builder = f.newDocumentBuilder();
    Document doc = builder.parse(...);
于 2013-04-17T08:33:34.513 回答