[英]Java XML String with attributes to NodeList (parsing)
我有一個字符串,其內容是一個 XML 文檔。
下面是一個字符串的例子。
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\" />";
我想將此字符串轉換為 NodeList。 谷歌搜索導致了這篇文章。
我嘗試了以下代碼:
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlContent));
Document doc = db.parse(is);
NodeList oNodeService = doc.getElementsByTagName("Service");
問題是我在“db.parse(is)”行上被撕了。 問題似乎是這種方法不支持 XML 屬性。
錯誤信息是:
[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)
如何成功將此 XML 字符串轉換為 NodeList?
更新:嗯,失敗是特定於 XML 字符串的。 我在上面給出了一個縮短的版本。 我刪除了所有不會導致崩潰的屬性。
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\" />";
如果我要冒險猜測,我會說是句號或破折號。 我想首先獲得此更新。
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.