繁体   English   中英

为子节点解析JDOM中的XML文件

[英]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.

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