我需要用 java 读取一个 XML 文件。文件结构如下。
<?xml version="1.0" encoding="UTF-8"?>
<xml_tool xmlns:md="http://www.example.com/XT/1.0/">
<md:header>
<md:application_version>1.0</md:application_version>
<md:export_date>19-04-2012</md:export_date>
<md:export_time>14:55</md:export_time>
<md:export_user>USER01</md:export_user>
</md:header>
<md:table table_name="CUSTOMER" key="customer number" record_count="2" column_count="5">
<md:record>
<md:column name="customer_number">123456</md:column>
<md:column name="reg_date">01-04-2012</md:column>
<md:column name="customer_name">Test Customer</md:column>
<md:column name="customer_type">Normal </md:column>
<md:column name="comments">This is a test record</md:column>
</md:record>
<md:record>
<md:column name="customer_number">555111</md:column>
<md:column name="reg_date">02-04-2012</md:column>
<md:column name="customer_name">Test Customer</md:column>
<md:column name="customer_type">VIP </md:column>
<md:column name="comments">This is a test record</md:column>
</md:record>
</md:table>
</xml_tool>
我已阅读How to read XML file in Java – (DOM Parser) example 并尝试完成我的工作。但我无法成功读取 XML 文件。
我的代码
try {
File fXmlFile = new File("c:\\file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("md:record");
for (int i = 0; i < nList.getLength(); i++) {
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) node;
System.out.println(getTagValue("md:column", eElement));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
结果是
123456
555111
我如何阅读这个 XML 文件?