【发布时间】:2020-05-09 10:12:20
【问题描述】:
我从 XML 标记中检索到了我需要的数据。 我在这方面使用了相关包。 现在我想将结果保存在 .txt 文件中,但我不知道如何在我的代码中使用 FileWriter? 我尝试了几次,但我得到了一个空白文本文件,控制台中没有打印结果。任何人都可以帮助我将结果保存为txt?
package XMLConvertor;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class Sample {
public static void main(String argv[]) {
try {
//SourceFile
File fXmlFile = new File("~/Downloads/Teacher.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
//归一化 doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
//Teacher name tags
NodeList nList = doc.getElementsByTagName("TeacherName");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Name: " + eElement.getElementsByTagName("Name").item(0).getTextContent());
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
【问题讨论】:
标签: java xml tags package simple-xml-converter