Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - parse nested xml file and write to the file

Tags:

java

xml

javax

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?

like image 287
EdXX Avatar asked Mar 22 '26 02:03

EdXX


1 Answers

Java - parse nested xml file and write to the file

A simple way :

  1. Read line by line with BufferedReader.readLine() until finding the start of the nested xml part.
    For example : <?xml version="1.0"?>

  2. 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>

  3. 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())));

  4. Use your preferred way to find data in the document : dom, jdom, xpath, etc...

like image 129
davidxxx Avatar answered Mar 25 '26 00:03

davidxxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!