0

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

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

4

1 回答 1

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

        }

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

于 2013-09-06T05:11:16.447 回答