开发者

getting grandchildren from xml in java

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 rootNo开发者_如何学JAVAde = 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


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");
   }
}


Use getElementsByTagName() to get the <paths> tag and then use it to get its children.

Oh that's for the w3c element. For the JDOM element jsut use getChild() and getChildren().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜