我需要将xml文件的内容打印到某个txt文件中.这是我要打印的xml类型的示例:
<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>
Run Code Online (Sandbox Code Playgroud)
我可以获得我需要的所有信息,除了路径标记...这就是我所做的:
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();
Run Code Online (Sandbox Code Playgroud)
那么,我是如何通过该标签获取信息的?
PS如果这是一个愚蠢的问题,请随意将其置于遗忘之中......只要你指引我回答:)
谢谢
您可以迭代paths孩子们:
...
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");
}
}
Run Code Online (Sandbox Code Playgroud)