简体   繁体   English

具有 NodeList 属性的 Java XML 字符串(解析)

[英]Java XML String with attributes to NodeList (parsing)

I have a string, whose contents is an XML document.我有一个字符串,其内容是一个 XML 文档。

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.我想将此字符串转换为 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.问题是我在“db.parse(is)”行上被撕了。 The problem seems to be that this method does not support XML attrihutes.问题似乎是这种方法不支持 XML 属性。

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?如何成功将此 XML 字符串转换为 NodeList?

UPDATE: Hmm, the failure is specific to the XML string.更新:嗯,失败是特定于 XML 字符串的。 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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