如何使用DOM解析n级xml

时间:2013-09-05 11:11:29

标签: xml dom xml-parsing

我需要解析一个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

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

1 个答案:

答案 0 :(得分:0)

将代码更改为

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

        }

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