I have a .xml file like below:
<?xml version="1.0"?>
<Event>
<Issue>ggg</Issue>
<City>Athen</City>
<Group>
<AlternateIdentification>
<AlternateID>DG800</AlternateID>
<AlternateIDType>GoA</AlternateIDType>
</AlternateIdentification>
<AlternateIdentification>
<AlternateID>SS500</AlternateID>
<AlternateIDType>SDD</AlternateIDType>
</AlternateIdentification>
<AlternateIdentification>
<AlternateID>TY158</AlternateID>
<AlternateIDType>YTU</AlternateIDType>
</AlternateIdentification>
</Group>
</Event>
And I would like to parse .xml file and write the output to the flat .txt file with lines like this:
ggg Athen DG800
ggg Athen SS500
ggg Athen TY158
Can you help me and tell me how to do this with javax DOM parser? I have no idea how to start :( This common part confuses me the most because I need to iterate this file in this case 3 times to get 3x "ggg Athen" and then additional tag AlternateID?
Java - parse nested xml file and write to the file
A simple way :
Read line by line with BufferedReader.readLine() until finding the start of the nested xml part.
For example : <?xml version="1.0"?>
When you identified this line, add each read line in a StringBuilder instance until you encounter the end of the xml part that you want to analyse. For example the end tag of the root element of it.
Here : </Event>
Create a org.w3c.dom.Document from the String contained in the StringBuilder :
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader( stringBuilder.toString())));
Use your preferred way to find data in the document : dom, jdom, xpath, etc...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With