【问题标题】:How to parse n-level xml using DOM如何使用 DOM 解析 n 级 xml
【发布时间】:2023-04-07 19:45:01
【问题描述】:

我需要解析一个 n 级 xml 文件并显示它的元素。它永远不会有任何属性。 我当前的代码

String xmlInputFile="reportA.xml"  ;
        File file =new File(xmlInputFile);
        Document document;
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory;
        NodeList nodeList;
        documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.parse(xmlInputFile);

        document.getDocumentElement().normalize();
         nodeList = document.getElementsByTagName("*");
        for (int index = 0; index < nodeList.getLength(); index++) {
            Node nodeA = nodeList.item(index);
            if (nodeA.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) nodeA;
                if(element.hasChildNodes()){
                    System.out.println("Name "+element.getNodeName()+" value "+element.getFirstChild().getNodeValue().trim());
                }
            }
        }

我的xml文件是

<?xml version="1.0" encoding="UTF-8" ?>
<company>
    <record>
        <name>
            <firstName>Brad</firstName>
            <lastName>Pitt</lastName>
        </name>
        <age>41</age>
        <dob>31/8/1982</dob>
        <income>200,000</income>
    </record>
</company>

当前输出是:

Name company value 
Name record value 
Name name value 
Name firstName value Brad
Name lastName value Pitt
Name age value 41
Name dob value 31/8/1982
Name income value 200,000

我不需要公司、记录、姓名。如何去除这些元素?

【问题讨论】:

    标签: xml dom xml-parsing


    【解决方案1】:

    把代码改成

    nodeList = document.getElementsByTagName("*");
            for (int index = 0; index < nodeList.getLength(); index++) {
                Node nodeA = nodeList.item(index);
               if (nodeA.getNodeType() == Node.ELEMENT_NODE) {
                   NodeList nodeList1 = nodeA.getChildNodes();
                   if(nodeList1.getLength()<=1 ){
                       String value="";
                        if(nodeList1.getLength()!=0){
                            value= nodeA.getFirstChild().getNodeValue();
                        } 
                        System.out.println("Name "+nodeA.getNodeName()+" value "+ value);
                   }
               }
    
            }
    

    现在只打印根节点。但是,我想看看是否有人有更好的主意..

    【讨论】:

      猜你喜欢
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 2012-11-18
      • 2012-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-19
      相关资源
      最近更新 更多