简体   繁体   中英

Java XML String with attributes to NodeList (parsing)

I have a string, whose contents is an XML document.

Here is an example of a string.

String xmlContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + 
"<Service oem=\"myOem\" agent=\"myAgent\" version=\"0.5.5.0\" build=\"30-01-2014-11-46\" />";

I want to convert this string to a NodeList. A Google search led to this article .

I tried the following code:

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlContent));
Document doc = db.parse(is);
NodeList oNodeService = doc.getElementsByTagName("Service");

The problem is that I get a rip on the "db.parse(is)" line. The problem seems to be that this method does not support XML attrihutes.

The error message is:

[Fatal Error] :1:70: Element type "Service" must be followed by either attribute specifications, ">" or "/>".
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 70; Element type "Service" must be followed by either attribute specifications, ">" or "/>".
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at PkgNetAccelerator32.MainEvents.ShowHtsInfo(MainEvents.java:1575)

How can I successfully convert this XML string to a NodeList?

UPDATE: Hmm, the failure is specific to the XML string. I gave a shortened version above. I removed all attributes that cause no crashes.

String xmlContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Service hostname=\"sarah-linux.localdomain\"uname=\"Linux sarah-linux.localdomain 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux\" />";

If I were to hazard a guess, I would say it is the period or the dash. I wanted to get this update in first.

    String xmlContent = "<System><rpm-items><rtmap-items><Rule-list><name>RoutingPolicy3</name></Rule-list></rtmap-items></rpm-items></System>";
    InputStream isr = new ByteArrayInputStream(xmlContent.getBytes(StandardCharsets.UTF_8));
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(isr);

    NodeList ruleList = doc.getElementsByTagName("System");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM