I am trying to parse this XML in Java:
<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>
But I just got the Entities scroll, getting all Entity and every <product_type> , <section_type> , etc. But I also want to scroll through the files.
This is my implementation:
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(); }
Function
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(); }
I did a lot of searching on Google, and all I find are simple examples with a parent and child, but not child.
Any help would be appreciated.
Reinherd
source share