I need help with writing a java code for parsing this xml file below. The structure confuses me. I am new to java coding .. I have read a number of codes for parsing xml files but the structure looks different from mine
<?xml version="1.0" encoding="utf-8"?>
<trafficDetectorData xmlns:xsi="http://ift.tt/ra1lAU" xmlns="http://ift.tt/1uW8LJ4" xmlns:lrms="http://ift.tt/1sL7esK" xsi:schemaLocation="http://ift.tt/1uW8LJ4 C:\temp\test\Detectors.xsd">
<owner-id>IADOT-SIMS</owner-id>
<network-id>IADOT-SIMS</network-id>
<collection-periods>
<collection-period>
<detection-time-stamp>
<local-date>20140928</local-date>
<local-time>221000</local-time>
<utc-offset>-0500</utc-offset>
</detection-time-stamp>
<start-time>221000</start-time>
<end-time>221020</end-time>
<detector-reports>
<detector-report>
<detector-id>I-74 NB from Ave of the Cities t</detector-id>
<status>operational</status>
<lanes>
<lane>
<lane-id>1</lane-id>
<count>1</count>
<volume>1</volume>
<occupancy>0</occupancy>
<speed>122</speed>
<classes>
<class>
<class-id>Small</class-id>
<count>1</count>
<volume>1</volume>
</class>
<class>
<class-id>Medium</class-id>
</class>
<class>
<class-id>Large</class-id>
</class>
</classes>
</lane>
</lanes>
</detector-report>
</detector-reports>
</collection-period>
</collection-periods>
</trafficDetectorData>
Below is the code I wrote for parsing the file above. My question is how do I add the values under lanes and classes?
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
public class FinalTrial {
public static void main(String argv[]) {
try {
File fXmlFile = new File("workFile_09282014 22-10-34c.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("detector-report");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Detector ID : " + eElement.getElementsByTagName("detector-id").item(0).getTextContent());
System.out.println("Status : " + eElement.getElementsByTagName("status").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
No comments:
Post a Comment