Note that there are some explanatory texts on larger screens.

plurals
  1. PODOM parser for Java prints same value
    primarykey
    data
    text
    <p>I have this xml file</p> <pre><code>&lt;Cdtr&gt; &lt;Nm&gt;DEF Electronics&lt;/Nm&gt; &lt;PstlAdr&gt; &lt;AdrLine&gt;Corn Exchange 5th Floor&lt;/AdrLine&gt; &lt;AdrLine&gt;Mark Lane 55&lt;/AdrLine&gt; &lt;AdrLine&gt;EC3R7NE London&lt;/AdrLine&gt; &lt;AdrLine&gt;GB&lt;/AdrLine&gt; &lt;/PstlAdr&gt; &lt;/Cdtr&gt; </code></pre> <p>I am trying to parse the xml, get leaf tags names(which has values) and their respective values using dom parser in Java. Following is the code i am using for that.</p> <pre><code>public class GetNodeValues { public static void main(String[] args) { try { String xmlFile = "C:/Users/Administrator/workspace/sample.xml"; File file = new File(xmlFile); if(file.exists()){ // Create a factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // Use the factory to create a builder DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile); doc.getDocumentElement().normalize(); // Get a list of all elements in the document NodeList list = doc.getElementsByTagName("*"); System.out.println("XML Elements: "); for (int i=0; i&lt;list.getLength(); i++) { // Get element Element element = (Element)list.item(i); String nodnam = element.getNodeName(); NodeList nl = doc.getElementsByTagName(nodnam); Element ele = (Element) nl.item(0); if (ele.getChildNodes().getLength() &gt; 0) // then it has text String val = ele.getChildNodes().item(0).getNodeValue(); if (val.startsWith("\n")) { //Discarding pseudo nodes }else { System.out.println("Node: "+nodnam+" | Val: "+val); //print node names and values } } } } else{ System.out.print("File not found!"); } } catch (Exception e) { System.exit(1); } } } </code></pre> <p>I am getting the following result.</p> <pre><code>Node: AdrLine | Val: Corn Exchange 5th Floor Node: AdrLine | Val: Corn Exchange 5th Floor Node: AdrLine | Val: Corn Exchange 5th Floor Node: AdrLine | Val: Corn Exchange 5th Floor </code></pre> <p>Please help. I am not understanding why its repeating the tag value. The expected output is</p> <pre><code>Node: AdrLine | Val: Corn Exchange 5th Floor Node: AdrLine | Val: Mark Lane 55 Node: AdrLine | Val: EC3R7NE London Node: AdrLine | Val: GB </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload