我需要解析一个 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
我不需要公司、记录、姓名。如何去除这些元素?