Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting grandchildren from xml in java

Tags:

java

xml

jdom

I need to print out the contents of an xml file into some txt file. Here is a sample of the type of xml i want to print out:

<log>
    <logentry revision="234">
        <author>SOMEGUY</author>
        <date>SOME DATE</date>
        <paths>
            <path>asdf/asdf/adsf/asdf.zip</path>
        </path>
        <msg>blahblahblah</msg>
    </logentry>
</log>

I can get all the information I need, except for the path tag... this is what I've done:

        FileWriter fstream = new FileWriter("c:\\work\\output.txt");
        BufferedWriter out = new BufferedWriter(fstream);

        Document document = (Document) builder.build(xmlFile);
        Element rootNode = document.getRootElement();
        List list = rootNode.getChildren("logentry");

        for (int i=0; i< list.size(); i++) {

            Element node = (Element) list.get(i);

            out.write("Revision: \n" + node.getAttributeValue("revision") + "\n\n");
            out.write("Author: \n"  + node.getChildText("author") + "\n\n");
            out.write("Date: \n"  + node.getChildText("date") + "\n\n");



            out.write("Message: \n"  + node.getChildText("msg"));
            out.write("\n-------------------------------------------------"
                    +"---------------------------------------------------\n\n");
        }
        out.close();

So, how the devil to I get the info from that tag?

P.S. Feel free to downvote this into oblivion if it's a stupid question... so long as you ALSO direct me towards an answer :)

Thanks

like image 850
Aelfhere Avatar asked Nov 13 '22 21:11

Aelfhere


1 Answers

You can iterate over the paths children:

...
List pathsChilds = node.getChildren("paths");
if(pathsChilds.size() > 0){
   Element paths = (Element)  pathsChilds.get(0);
   List pathChilds = paths.getChildren("path");
   for (int j=0; j< pathChilds.size(); j++) {
      Element path = (Element) pathChilds.get(j);
      out.write("Path: \n"  + path.getText() + "\n\n");
   }
}
like image 71
morja Avatar answered Dec 16 '22 13:12

morja