2015-10-08 62 views
1

我有以下方式的XML文件:解析在JDOM的孩子,孩子一个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解析器解析,并得到相应的值。 我需要把值列表中的信息。

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"); 

我没有得到如何进一步处理和使用列表。

回答

0

先上去,请确保您使用的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(...)返回一个列表,这样就不能工作。在我的代码中,我反复遍历列表。如果只有一个“info”元素,那么该列表将只有一个成员。

另请注意,在JDOM 2.x中,getChildren(..)方法返回元素列表:List<Element>,因此不需要将结果转换为Element

0

这可以使用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); 
相关问题