我正在开发一个涉及解析此示例.xml文件的项目(如下所示)但是我没有得到预期的输出。当我在下面运行此代码时,它具有与“parseout.xml”输出中不同的控制台输出。输出文件“parseout.xml”具有相同的原始文件内容。如何将控制台输出导出到不同的xml文件中?
示例文件(在我的代码之后注意它仍然将它输出到“parseout.xml”,这是输出.xml文件:
<?xml version="1.0"?>
<schedule id="backup" duration="86400">
<datapoint time="0" speed="1" speednoise=".5" concurrency="8" concurrencynoise="1" interval="300" intervalnoise="300"/> <!-- 12am -->
<datapoint time="7200" speed="1" speednoise=".5" concurrency="8" concurrencynoise="1" interval="300" intervalnoise="300"/> <!-- 2am -->
<datapoint time="7201" speed="1" speednoise=".5" concurrency="0" concurrencynoise="0" interval="300" intervalnoise="300"/> <!-- 2:00:01am -->
<datapoint time="86399" speed="1" speednoise=".5" concurrency="0" concurrencynoise="0" interval="10" intervalnoise="0"/> <!-- 11:59:59pm -->
</schedule>
代码:
File fXmlFile = new File(originalfile.xml);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
// System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("datapoint");
// 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("Time:" + eElement.getAttribute("time"));
System.out.println("Speed:" + eElement.getAttribute("speed"));
System.out.println("SpeedNoise:" + eElement.getAttribute("speednoise"));
System.out.println("Concurrency:" + eElement.getAttribute("concurrency"));
System.out.println("ConcurrencyNoise:" + eElement.getAttribute("concurrencynoise"));
System.out.println("Interval: " + eElement.getAttribute("interval"));
System.out.println("IntervalNoise: " + eElement.getAttribute("intervalnoise"));
//Using transformer for output
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("parseout.xml"));
transformer.transform(source, result);
}
}