有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java解析JDOM中用于子节点的XML文件

我有以下方式的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>

我需要使用JavaDOM解析器对其进行解析,并获得相应的值。 我需要将值放在列表中的“信息”下

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

我不知道如何进一步使用列表


共 (2) 个答案

  1. # 1 楼答案

    这是可行的,使用javax中的东西。xml。解析器和组织。w3c。多姆

    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 );
    
  2. # 2 楼答案

    首先,请确保您使用的是JDOM 2.0.6(如果您以后阅读本文,请确保使用的是JDOM 2.0.6或更高版本)。jdom2。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());
            }
        }
    }
    

    注意,我在这里放了两个循环。您的代码有一个bug,因为它调用:

    Element info = rootNode.getChildren("info");
    

    但是getChildren(...)返回一个列表,因此无法工作。在上面的代码中,我遍历了列表。如果只有一个“info”元素,那么列表将只有一个成员

    还要注意,在JDOM2中。x、 getChildren(..)方法返回一个元素列表:List<Element>,因此无需将结果强制转换为Element