[英]Parsing an XML file in JDOM for child-child nodes
我有以下方式的XML文件:
<head>
<username>bhnsub</username>
<error>0</error>
<account_id>633</account_id>
<info>
<mac>address_goes_here<mac>
<mac>address_goes_here</mac>
<mac>address_goes_here</mac>
<mac>address_goes_here</mac>
<mac>address_goes_here<mac>
</info>
</head>
我需要使用Java DOM解析器解析它並獲取相應的值。 我需要將值放在info下的列表中。
SAXBuilder builder = new SAXBuilder();
Document document = (Document) builder.build(new StringReader(content));
Element rootNode = document.getRootElement();
if (rootNode.getName().equals("head")) {
String username = rootNode.getChildText("username");
String error= rootNode.getChildText("error");
String account= rootNode.getChildText("account_id");
Element info= rootNode.getChildren("info");
List mac=info.getChildren("mac");
我不知道如何繼續進行和使用列表。
這可以使用javax.xml.parsers和org.w3c.dom中的內容進行工作。
List<String> macvals = new ArrayList<>();
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(new File( "head.xml" ) );
Element rootNode = document.getDocumentElement();
if (rootNode.getTagName().equals("head")) {
NodeList infos = rootNode.getElementsByTagName("info");
if( infos.getLength() > 0 ){
Element info = (Element)infos.item(0);
NodeList macs = info.getElementsByTagName("mac");
for( int i = 0; i < macs.getLength(); ++i ){
macvals.add( macs.item( i ).getTextContent() );
}
}
}
System.out.println( macvals );
首先,請確保您使用的是JDOM 2.0.6(或更高版本,如果將來要閱讀的話)。 JDOM 2.x已經問世5年了,它更好,因為它支持Java泛型,具有性能改進,並且如果需要,它也具有更好的XPath支持。
盡管如此,您的代碼仍將“輕松”編寫為:
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new StringReader(content));
Element rootNode = document.getRootElement();
if ("head".equals(rootNode.getName())) {
String username = rootNode.getChildText("username");
String error= rootNode.getChildText("error");
String account= rootNode.getChildText("account_id");
List<String> macs = new ArrayList<>();
for (Element info : rootNode.getChildren("info")) {
for (Element mac : info.getChildren("mac")) {
macs.add(mac.getValue());
}
}
}
請注意,我在其中放置了2個循環。 您的代碼有一個錯誤,因為它調用:
Element info = rootNode.getChildren("info");
但是getChildren(...)
返回一個List,因此無法正常工作。 在上面的代碼中,我改為遍歷該列表。 如果只有一個“ info”元素,則列表將只有一個成員。
還要注意,在JDOM 2.x中, getChildren(..)
方法返回Element的列表: List<Element>
因此無需將結果轉換為Element
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.