Java code for parsing a complex XML file - java

Below is a program written to parse the accompanying XML file.
Problem: There are two lane-IDs, but the output of my code keeps outputting only one. I expect the output to be:
Current Element: detector-report
Detector ID : I-74 NB from 12th Ave to 7th Ave
Status : operational
Lane-ID : 1
Lane - ID: 2
The current code still outputs 1 on the last line.
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());
NodeList lanes = eElement.getElementsByTagName("lane");
System.out.println(lanes.getLength());
for (int j = 0; j<lanes.getLength(); j++) {
Element lane = (Element) lanes.item(0);
System.out.println("Lane-ID : " + lane.getElementsByTagName("lane-id").item(0).getTextContent());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Below is the accompanying XML file:
<?xml version="1.0" encoding="utf-8"?>
<trafficDetectorData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.dummy-temp-address" xmlns:lrms="http://www.dummy-lrms-address" xsi:schemaLocation="http://www.dummy-temp-address C:\temp\test\Detectors.xsd">
<detector-report>
<detector-id>I-74 NB from Ave of the Cities t</detector-id>
<status>operational</status>
<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>
<lane>
<lane-id>2</lane-id>
<occupancy>0</occupancy>
<speed>137</speed>
<classes>
<class>
<class-id>Small</class-id>
</class>
<class>
<class-id>Medium</class-id>
</class>
<class>
<class-id>Large</class-id>
</class>
</classes>
</lane>
</detector-report>
<detector-report>
<detector-id>I-74 NB from 12th Ave to 7th Ave</detector-id>
<status>operational</status>
<lane>
<lane-id>1</lane-id>
<count>3</count>
<volume>3</volume>
<occupancy>3</occupancy>
<speed>100</speed>
<classes>
<class>
<class-id>Small</class-id>
<count>3</count>
<volume>3</volume>
</class>
<class>
<class-id>Medium</class-id>
</class>
<class>
<class-id>Large</class-id>
</class>
</classes>
</lane>
<lane>
<lane-id>2</lane-id>
<count>4</count>
<volume>4</volume>
<occupancy>3</occupancy>
<speed>116</speed>
<classes>
<class>
<class-id>Small</class-id>
<count>4</count>
<volume>4</volume>
</class>
<class>
<class-id>Medium</class-id>
</class>
<class>
<class-id>Large</class-id>
</class>
</classes>
</lane>
</detector-report>
</trafficDetectorData>

I urge most developers to use established libraries for XML document handling, to avoid errors such as not properly escaping attribute values.
Java's built-in XML parsing library works very well (org.w3c.dom.Document, etc...).

Related

Extract values for more than one attribute node values via XPath expression

How can I extract value of more than one attribute node via XPath expression?
A sample XML file is:
<tag1>
<tag2>
<tag3 id="1">
<tage4>
<tage4code code="1">
<tag5>
<tage4Value Day="14" Month="Oct" Year="2000" />
</tag5>
<tag5>
<tage4Value Month="Oct" Year="2001" />
</tag5>
<tag5>
<tage4Value Year="2002" />
</tag5>
<tag5>
<tage4Value Day="1" Month="Jan" Year="1999" />
</tag5>
<tag5>
<tage4Value Year="1940" />
</tag5>
</tage4code>
</tage4>
</tag3>
</tag2>
</tag1>
So far I have this XPath string:
XPathExpression expr = xpath.compile("concat((/tag1/tag2/tag3[#id=1]/tage4/tage4code[#code=1]/tag5/tage4Value/#Day, '/' , /tag1/tag2/tag3[#id=1]/tage4/tage4code[#code=1]/tag5/tage4Value/#Month, '/', /tag1/tag2/tag3[#id=1]/tage4/tage4code[#code=1]/tag5/tage4Value/#Year)");
NodeList combination1 = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for (int a = 0; a <= combination1.getLength(); a++) {
System.out.println("date : " + combination.item(a).getNodeValue());
}
My Expected result
14/Oct/2000
Oct/2001
2002
1/Jan/1999
1940
Can someone help to correct my XPathExpression
XPath 2.0 solution :
tokenize(replace(replace(replace(substring-after(string-join(//tag5/*|//tag5//#*,","),","),",,","%"),","," ")," ","/"),"%")
Output :
String='14/Oct/2000'
String='Oct/2001'
String='2002'
String='1/Jan/1999'
String='1940'
XPath 1.0 solution :
concat(translate(normalize-space(concat((//tage4Value)[1]/#Day," ",(//tage4Value)[1]/#Month," ",(//tage4Value)[1]/#Year))," ","/"),"|",translate(normalize-space(concat((//tage4Value)[2]/#Day," ",(//tage4Value)[2]/#Month," ",(//tage4Value)[2]/#Year))," ","/"),"|",translate(normalize-space(concat((//tage4Value)[3]/#Day," ",(//tage4Value)[3]/#Month," ",(//tage4Value)[3]/#Year))," ","/"),"|",translate(normalize-space(concat((//tage4Value)[4]/#Day," ",(//tage4Value)[4]/#Month," ",(//tage4Value)[4]/#Year))," ","/"),"|",translate(normalize-space(concat((//tage4Value)[5]/#Day," ",(//tage4Value)[5]/#Month," ",(//tage4Value)[5]/#Year))," ","/"))
Output :
String='14/Oct/2000|Oct/2001|2002|1/Jan/1999|1940'
Or with new line separator :
concat(translate(normalize-space(concat((//tage4Value)[1]/#Day," ",(//tage4Value)[1]/#Month," ",(//tage4Value)[1]/#Year))," ","/"),codepoints-to-string(10),translate(normalize-space(concat((//tage4Value)[2]/#Day," ",(//tage4Value)[2]/#Month," ",(//tage4Value)[2]/#Year))," ","/"),codepoints-to-string(10),translate(normalize-space(concat((//tage4Value)[3]/#Day," ",(//tage4Value)[3]/#Month," ",(//tage4Value)[3]/#Year))," ","/"),codepoints-to-string(10),translate(normalize-space(concat((//tage4Value)[4]/#Day," ",(//tage4Value)[4]/#Month," ",(//tage4Value)[4]/#Year))," ","/"),codepoints-to-string(10),translate(normalize-space(concat((//tage4Value)[5]/#Day," ",(//tage4Value)[5]/#Month," ",(//tage4Value)[5]/#Year))," ","/"))
Output :
String='14/Oct/2000
Oct/2001
2002
1/Jan/1999
1940'
This xpath expression
//tag3[#id="1"]//tage4code[#code=1]//tag5/tage4Value/concat(#Day,'/',#Month,'/',#Year)
should output
14/Oct/2000
/Oct/2001
//2002
1/Jan/1999
//1940
This way we can create a dynamic way of reading the child.
xpathExpression = "count(//tag1/tag2/tag3[#id=1]/tage4/tage4code[#code=1]/tag5/tage4Value)";
double nodeList1 = (double) xpath.compile(xpathExpression).evaluate(doc, XPathConstants.NUMBER);
int s = (int) (nodeList1);
for (int z = 1; z <= s; z++) {
xpathExpression = "normalize-space(concat((//tag1/tag2/tag3[#id=1]/tage4/tage4code[#code=1]/tag5/tage4Value)["
+ z
+ "]/#Day,\" \",(//tag1/tag2/tag3[#id=1]/tage4/tage4code[#code=1]/tag5/tage4Value)["
+ z
+ "]/#Month,\" \",(//tag1/tag2/tag3[#id=1]/tage4/tage4code[#code=1]/tag5/tage4Value)["
+ z + "]/#Year))";
String year = (String) xpath.evaluate(xpathExpression, doc, XPathConstants.STRING);
System.out.println(year);
}

Creating an intermediate graph from XML file of UML activity diagram in java

I have an XML generated for an UML activity diagram. I want to generate a tree structure for XML so I could find possible transition paths. Tried with DOMXML java parser but no results. I need to group activity as nodes and transitions as edges. Also attached XML file. enter image description herePlease help
Java Code
public class DomXMLParser {
public static void main(String[] args) throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
//DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
File fXmlFile = new File("C:/Projekte/activity.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
javax.xml.xpath.XPathExpression expr
= xpath.compile("//xmi:XMI[xmi:type ='uml:Activity']/name/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
Eclipse Modeling Framework (EMF) design to read UML models. I write a code to Read UML Class Diagram reading with EMF. You design you model in Enterprise Architect so export as UMl model or design in papyrus which build on EMF
<?xml version="1.0" encoding="windows-1252"?>
<xmi:XMI xmi:version="2.1" xmlns:uml="http://schema.omg.org/spec/UML/2.1" xmlns:xmi="http://schema.omg.org/spec/XMI/2.1" xmlns:StandardProfileL2="http://www.omg.org/spec/UML/20110701/StandardProfileL2.xmi">
<xmi:Documentation exporter="Enterprise Architect" exporterVersion="6.5"/>
<uml:Model xmi:type="uml:Model" name="EA_Model" visibility="public">
<packagedElement xmi:type="uml:Package"xmi:id="EAPK_263A2FE8_8346_4d1e_A851_39B9D573143D" name="Activity Model" visibility="public">
<ownedComment xmi:type="uml:Comment" xmi:id="EAID_DDCEE555_5FD6_487c_BB82_A5F055D67309" body="Case 3: Btn_Pressed = 3">
<annotatedElement xmi:idref="EAID_367AB5AB_2A9C_4387_B4A2_2974CE57D11E"/>
</ownedComment>
<packagedElement xmi:type="uml:Activity" xmi:id="EAID_A165F2B1_D71E_4c10_8EB4_745B37742C0F" name="Start CnrtLk_Main()" visibility="public" isReadOnly="false" isSingleExecution="false"/>
<edge xmi:type="uml:ControlFlow" xmi:id="EAID_5350396C_9C67_4190_817C_9EEF1E34582C" visibility="public" source="EAID_A165F2B1_D71E_4c10_8EB4_745B37742C0F" target="EAID_6428B619_8065_4a57_99CD_8F19CFB6F136"/>
<packagedElement xmi:type="uml:Activity" xmi:id="EAID_6428B619_8065_4a57_99CD_8F19CFB6F136" name="Get Parameters" visibility="public" isReadOnly="false" isSingleExecution="false"/>
<edge xmi:type="uml:ControlFlow" xmi:id="EAID_A0B50908_8ADF_4507_8033_E77D777E21DD" visibility="public" source="EAID_6428B619_8065_4a57_99CD_8F19CFB6F136" target="EAID_32296133_1810_41c5_9A4D_6D3B6F11FF52"/>
<node xmi:type="uml:InitialNode" xmi:id="EAID_CF9A7618_F1C4_4395_94D5_D2F483A51119" name="System_Initial" visibility="public">
<outgoing xmi:idref="EAID_2785D6B4_D4DF_442f_AF8B_657D85367743"/>
</node>
<node xmi:type="uml:ActivityFinalNode" xmi:id="EAID_D2EB427B_3AFD_4700_BD72_13B36684E595" name="ActivityFinal" visibility="public">
<incoming xmi:idref="EAID_E036A3F5_4C88_4471_9C2F_031554144E9E"/>
<incoming xmi:idref="EAID_D62F8934_F4E6_4b00_A35B_E1149E4C06E6"/>
<incoming xmi:idref="EAID_CC1E7F54_9C97_4aec_AE53_55AD4DA43408"/>
<incoming xmi:idref="EAID_ADD5D207_728A_4aeb_80EB_F9542CF6ED80"/>
<incoming xmi:idref="EAID_873CF8C4_0192_4099_8F66_6B36FA760AB6"/>
<incoming xmi:idref="EAID_6B8D52FB_C522_4bda_BE10_B5080F9F0B0D"/>
<incoming xmi:idref="EAID_417A863C_D59C_4c5e_8F38_60B1DC36B077"/>
</node>
<node xmi:type="uml:DecisionNode" xmi:id="EAID_0D85B784_4393_429e_9BA1_7983BD7891CA" name="decision1" visibility="public">
<incoming xmi:idref="EAID_1FAD9B0B_04ED_4f6a_B359_8755C3A3CA03"/>
<outgoing xmi:idref="EAID_32A43FB9_D99D_4c3c_8382_D899FD995BA7"/>
<outgoing xmi:idref="EAID_2FECE2AE_6CA0_48a4_82AE_D743D257F37C"/>
</node>
</packagedElement>
</packagedElement>

XML generation, element is being added incorrectly

I am writing a method which adds few element under the same root element in a loop but when I open the XML file it look like the first element is added correctly and the other ones are added under main element.
This is my method addStepElement():
DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
document.getDocumentElement().normalize();
Element rootElement = null;
NodeList findRootElementList = document.getElementsByTagName("testDetails");
for(int iterator = 0; iterator < findRootElementList.getLength(); iterator++) {
Node node = findRootElementList.item(iterator);
if(node.getNodeName().equals("testDetails")) {
rootElement = (Element)node;
}
}
Element step = document.createElement("Step");
rootElement.appendChild(step);
step.setAttribute("Step", "className");
step.setAttribute("result", "PASS");
step.setAttribute("screenshot", "file.jpg");
step.setAttribute("input", "email");
step.setAttribute("element", "submit");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5");
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File(file.getAbsolutePath()));
transformer.transform(source, result);
This is my output XML:
<Test>
<testDetails date="19-05-2016" testName="Test" time="11:24:14">
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
</testDetails>
</Test>
This is what I want to achieve:
<Test>
<testDetails date="19-05-2016" testName="Test" time="11:24:14">
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
<Step Step="className" element="submit" input="email" result="PASS" screenshot="file.jpg"/>
</testDetails>
</Test>
I do my method in a loop:
for(int i = 0; i < 5; i++) {
addStepElement();
}
What do I do wrong?
There is nothing wrong with the code as it produces an equivalent XML.
Indentation makes XML easier to read by human eye, but it doesn't change the meaning of XML whatsoever. All <Step> elements in the first XML are children of <testDetails> just like those <Step> elements in the 2nd XML. No difference in XML point of view.

NullPointerException when importing XML-file into Processing, Java

I'm trying to get data from an XML-file and use this data in processing. When doing so I get a NPE, and I can't quite figure out where I'm wrong. The XML got several layers and I have to get data from this "child":
http://i62.tinypic.com/2mb90g.png
My code looks like this:
XML xml;
void setup(){
xml = loadXML("parker.xml");
XML[] children = xml.getChildren("kml");
XML[] Folder=children[0].getChildren("Folder");
XML[] Placemark=Folder[1].getChildren("Placemark");
XML[] Polygon=Placemark[2].getChildren("Polygon");
XML[] outerBoundaryIs=Polygon[3].getChildren("outerBoundaryIs");
XML[] LinearRing=outerBoundaryIs[4].getChildren("LinearRing");
for (int i = 0; i < LinearRing.length; i++) {
float coordinates = children[i].getFloat("coordinates");
println(coordinates);
}
}
Best Chris
Stack trace:
[Fatal Error] :1:1: Content is not allowed in prolog.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content
is not allowed in prolog. at
com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:257)
at
com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:347)
at processing.data.XML.(XML.java:187) at
processing.core.PApplet.loadXML(PApplet.java:6310) at
processing.core.PApplet.loadXML(PApplet.java:6300) at
XMLtryout.setup(XMLtryout.java:21) at
processing.core.PApplet.handleDraw(PApplet.java:2359) at
processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:240)
at processing.core.PApplet.run(PApplet.java:2254) at
java.lang.Thread.run(Thread.java:744)
XML file:
https://www.dropbox.com/s/xn3thjskhlf2wai/parker.xml
This error maybe caused because missing this at the top of your xml file
<?xml version="1.0" encoding="utf-8"?>
or there's some non-printable garbage at the start of your file.
The 'Content is not allowed in prolog' error indicates that you have some content between the XML declaration and the appearance of the document element, for example
<?xml version="1.0" encoding="utf-8"?>
content here is not allowed
<kml xmlns="http://earth.google.com/kml/2.1">
...
</kml>
The XML file you linked is ok though, so it seems you're
reading the XML binary incorrectly before passing it to the XML parser,
or (more likely) you're not reading the XML at all (can happen when you read from a web URL and getting an error response). I assume you get a HTTP 40x error which you don't recognize, and read the response (usually HTML) as XML, which causes the error. Remember that applets usually can only read resources from the same server (that's what might cause the error).
To verify this, attempt to read the URL content and output it as text, and check if it looks ok.
Make it more easy
try like this
public static void setUp(){
try {
File file = new File("parker.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("LinearRing");
System.out.println("Information");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("coordinates");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
System.out.println("coordinates : " + ((Node) fstNm.item(0)).getNodeValue());
//
//
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
that should display :
Root element kml
Information
coordinates :
10.088512,56.154109,0
10.088512,56.154109,0
10.088512,56.154109,0
10.088511,56.15411,0
10.088511,56.15411,0
10.08851,56.15411,0
10.08851,56.154111,0
10.088509,56.154111,0
10.088508,56.154111,0
10.088508,56.154111,0
10.088507,56.154111,0
10.088506,56.154111,0
10.088506,56.154111,0
10.088505,56.154111,0
10.088504,56.154111,0
10.088504,56.154111,0
10.088503,56.15411,0
10.088503,56.15411,0
10.088502,56.15411,0
10.088502,56.154109,0
10.088502,56.154109,0
10.088501,56.154109,0
10.088501,56.154108,0
10.088501,56.154108,0
10.088501,56.154108,0
10.088501,56.154107,0
10.088285,56.154094,0
10.088104,56.154372,0
10.088061,56.154401,0
10.087988,56.15445,0
10.087915,56.154611,0
10.08791,56.154613,0
10.087912,56.154613,0
10.087877,56.1548,0
10.08772,56.15482,0
10.087558,56.154911,0
10.087421,56.155111,0
10.087316,56.155308,0
10.087328,56.15538,0
10.087372,56.155413,0
10.087446,56.155453,0
10.087484,56.155487,0
10.08747,56.155601,0
10.08772,56.155616,0
10.087719,56.155618,0
10.088618,56.155671,0
10.089096,56.1557,0
10.089096,56.155699,0
10.089138,56.155701,0
10.089127,56.155706,0
10.089004,56.155787,0
10.08888,56.155853,0
10.088799,56.155806,0
10.088571,56.155914,0
10.088455,56.155946,0
10.088112,56.156081,0
10.088184,56.156138,0
10.087733,56.156353,0
10.087489,56.156421,0
10.087288,56.156341,0
10.087268,56.156333,0
10.086893,56.156182,0
10.08684,56.156271,0
10.087049,56.156373,0
10.086893,56.156455,0
10.086664,56.156575,0
10.086443,56.156698,0
10.086425,56.156708,0
10.085983,56.156955,0
10.085655,56.157139,0
10.085462,56.157276,0
10.085272,56.157233,0
10.085176,56.157328,0
10.084917,56.157393,0
10.084883,56.157458,0
10.08495,56.157513,0
10.084947,56.157524,0
10.084943,56.157539,0
10.084855,56.15787,0
10.084855,56.15787,0
10.084321,56.157317,0
10.085553,56.156195,0
10.085555,56.156194,0
10.085553,56.156194,0
10.085734,56.156035,0
10.085821,56.155977,0
10.085937,56.155932,0
10.085993,56.155942,0
10.086031,56.155959,0
10.086171,56.15592,0
10.086227,56.155901,0
10.086392,56.155841,0
10.086513,56.155786,0
10.08664,56.155699,0
10.086686,56.155657,0
10.086727,56.155605,0
10.086777,56.155486,0
10.086861,56.155289,0
10.086916,56.155134,0
10.087006,56.154899,0
10.087075,56.154706,0
10.087094,56.154649,0
10.0871,56.154574,0
10.087112,56.154464,0
10.087111,56.154362,0
10.087112,56.154279,0
10.087112,56.154279,0
10.087113,56.15427,0
10.087114,56.154198,0
10.087108,56.15413,0
10.087091,56.154054,0
10.086992,56.153698,0
10.087,56.153678,0
10.087031,56.153647,0
10.087036,56.153648,0
10.087046,56.153652,0
10.087035,56.153647,0
10.087039,56.153645,0
10.087072,56.153612,0
10.087367,56.153308,0
10.087371,56.153303,0
10.08742,56.15323,0
10.087568,56.152963,0
10.087568,56.152962,0
10.087569,56.152962,0
10.08757,56.152961,0
10.087571,56.15296,0
10.087573,56.152959,0
10.087574,56.152959,0
10.087575,56.152958,0
10.087577,56.152958,0
10.087579,56.152958,0
10.087581,56.152957,0
10.087582,56.152957,0
10.087584,56.152957,0
10.087586,56.152958,0
10.087588,56.152958,0
10.087589,56.152958,0
10.087591,56.152959,0
10.087592,56.152959,0
10.087593,56.15296,0
10.087594,56.152961,0
10.087595,56.152962,0
10.087596,56.152963,0
10.087596,56.152964,0
10.087596,56.152965,0
10.087596,56.152965,0
10.087614,56.152967,0
10.087921,56.152988,0
10.088134,56.153019,0
10.088311,56.15304,0
10.088454,56.153052,0
10.088469,56.153378,0
10.08847,56.153445,0
10.088473,56.153597,0
10.088473,56.153597,0
10.088473,56.153597,0
10.088703,56.153614,0
10.088703,56.153614,0
10.088703,56.153614,0
10.088704,56.153614,0
10.088705,56.153614,0
10.088705,56.153615,0
10.088706,56.153615,0
10.088706,56.153615,0
10.088707,56.153616,0
10.088707,56.153616,0
10.088707,56.153616,0
10.088707,56.153617,0
10.088707,56.153617,0
10.088707,56.153617,0
10.088707,56.153618,0
10.088512,56.154108,0
10.088512,56.154109,0
coordinates :
10.086779,56.155487,0
10.086778,56.155488,0
10.086779,56.155487,0
10.086779,56.155487,0
coordinates :
10.08847,56.153602,0
10.088469,56.153602,0
10.088469,56.153602,0
10.08847,56.153602,0
PS : kml is the root element

Parse Specific Elements DOM - Java

I believe this is a simple question but I am having trouble to find out how it works.
That's the XML file (from www.w3schools.com):
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
As you can see the book XQuery Kick Start has more than one author.
But I cant find a way to get the right number of authors.
Thats my code:
public static void main(String argv[]) throws ParserConfigurationException, SAXException, IOException {
File fXmlFile = new File("\books.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("book");
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("Category : " + eElement.getAttribute("category"));
System.out.println("Title : " + eElement.getElementsByTagName("title").item(0).getTextContent());
System.out.println("Author : " + eElement.getElementsByTagName("author").item(0).getTextContent());
System.out.println("Year : " + eElement.getElementsByTagName("year").item(0).getTextContent());
System.out.println("Price : " + eElement.getElementsByTagName("price").item(0).getTextContent());
}
}
But as Result I'll be getting only one author:
Root element :bookstore
----------------------------
Current Element :book
Categoria do Livro : cooking
Titulo : Everyday Italian
Autor : Giada De Laurentiis
Ano : 2005
Price : 30.00
Current Element :book
Categoria do Livro : children
Titulo : Harry Potter
Autor : J K. Rowling
Ano : 2005
Price : 29.99
Current Element :book
Categoria do Livro : web
Titulo : XQuery Kick Start
Autor : James McGovern
Ano : 2003
Price : 49.99
Current Element :book
Categoria do Livro : web
Titulo : Learning XML
Autor : Erik T. Ray
Ano : 2003
Price : 39.95
Does anyone knows a good method to get the right number of elements?
sorry about the long question, I didnt know how to express myself so I had to paste here
*I'm new to DOM*
You're are getting the first author always, as you're retrieving the first item of the nodelist
getElementsByTagName("author").item(0)
Try iterating them, as there could be more than one
for (int i = 0; i < eElement.getElementsByTagName("author").getLength(); i++)
System.out.println("Author : " +
eElement.getElementsByTagName("author").item(i).getTextContent());

Categories

Resources