我正在尝试用 Java 解析这个 XML:
<entities>
<entity name="product_section" id="1">
<product_type>3</product_type>
<section_type>1</section_type>
<name>Empresa</name>
<description>d</description>
<position>1</position>
<align>left</align>
<files section_id="1">
<ico id="ico_1" type="normal" src="sections/1/icons/ico.png"></ico>
<ico id="ico_2" type="hover" src="sections/1/icons/ico.png"></ico>
<ico id="ico_3" type="active" src="sections/1/icons/ico.png"></ico>
<img id="img_1" type="normal" src="sections/1/img/pestanya.png"></img>
<img id="img_2" type="hover" src="sections/1/img/pestanya-hover.png"></img>
<img id="img_3" type="active" src="sections/1/img/pestanya-active.png"></img>
<background id="background_1" type="background" position="1" src="sections/1/background/bg1.png"></background>
<background id="background_2" type="background" position="2" src="sections/1/background/bg2.png"></background>
<background id="background_3" type="background" position="3" src="sections/1/background/bg3.png"></background>
</files>
</entity>
但是我刚刚实现了遍历实体,获取所有实体和每个<product_type>
,<section_type>
等等。但我也想遍历文件。
到目前为止,这是我的实现:
try {
File contingut = new File("xmlfile.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(contingut);
doc.getDocumentElement().normalize();
System.out.println("root of xml file " + doc.getDocumentElement().getNodeName());
//loop a cada entity
NodeList nodes = doc.getElementsByTagName("entity");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
Element element = (Element) node;
System.out.println("product_type: " + getValue("product_type", element));
System.out.println("section_type: " + getValue("section_type", element));
System.out.println("name: " + getValue("name", element));
System.out.println("description: " + getValue("description", element));
System.out.println("position: " + getValue("position", element));
System.out.println("align: " + getValue("align", element));
}
} catch (Exception e){
e.printStackTrace();
}
getValue
功能是:
private static String getValue(String tag, Element element) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
我做了很多谷歌搜索,我发现的只是“简单”的例子,有父母和孩子,但不是孩子的孩子。
任何帮助,将不胜感激。