Java DOM:无法将适配的XML写入文件

时间:2012-03-16 10:59:36

标签: java xml dom

我有以下简化的XML:

<?xml version="1.0" encoding="UTF-8"?>
<ExportData>
<Rows>
    <R>
        <companyCodestringtrue>101</companyCodestringtrue>
        <transactionQualifierstring>Sales</transactionQualifierstring>
        <menuItemNumberlong>4302150</menuItemNumberlong>
        <productQuantityinttrue>14</productQuantityinttrue>
        <productValueInclVATdecimaltrue>1.90</productValueInclVATdecimaltrue>
        <productValueExclVATdecimaltrue>1.775701</productValueExclVATdecimaltrue>
    </R>
    <R>
        <companyCodestringtrue>101</companyCodestringtrue>
        <transactionQualifierstring>Sales</transactionQualifierstring>
        <menuItemNumberlong>333555</menuItemNumberlong>
        <productQuantityinttrue>0</productQuantityinttrue>
        <productValueInclVATdecimaltrue>3.90</productValueInclVATdecimaltrue>
        <productValueExclVATdecimaltrue>3.775701</productValueExclVATdecimaltrue>
    </R>
    <R>
        <companyCodestringtrue>101</companyCodestringtrue>
        <transactionQualifierstring>Sales</transactionQualifierstring>
        <menuItemNumberlong>1235665</menuItemNumberlong>
        <productQuantityinttrue>5</productQuantityinttrue>
        <productValueInclVATdecimaltrue>4.90</productValueInclVATdecimaltrue>
        <productValueExclVATdecimaltrue>4.775701</productValueExclVATdecimaltrue>
    </R>
</Rows>
</ExportData>

如果<R>元素等于“0”,我需要删除每个完整的<productQuantityinttrue>元素。

我提出了以下Java代码:

package filterPositions;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class FilterPositions {

public static String result = "";

public static void main(String[] args) throws Exception {
    try {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); 
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        File filePath = new File("C:/LSA_SALES_EXPORT_1507_test_zero_qu.xml");
        Document doc = docBuilder.parse(filePath);

        Node rootNode = doc.getDocumentElement();
        final Element element = doc.getDocumentElement();

        // output new XML Document
        DocumentBuilder parser = docFactory.newDocumentBuilder();
        Document newdoc = parser.newDocument();
        newdoc.adoptNode(traversingXML(element));

        writeXmlFile(newdoc, "LSA_SALES_EXPORT_1507_test_zero_qu_OUT.xml");
        System.out.println("Done...");
        System.out.println("Exiting...");

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static Element traversingXML(Element element) {
    NodeList positionen = element.getElementsByTagName("R");
    Element e = null;
    for (int i = 0; i < positionen.getLength(); i++) {
        e = (Element) positionen.item(i);
        for (Node child = e.getFirstChild(); child != null; child = child.getNextSibling()) {
            if (child instanceof Element && "productQuantityinttrue".equals(child.getNodeName())&& "0".equals(child.getTextContent())) {
                e.getParentNode().removeChild(e);
            }
        }
    }
    System.out.println(e);
    return e;
}

public static void writeXmlFile(Document doc, String filename) {
    try {
        // Prepare the DOM document for writing
        Source source = new DOMSource();

        // Prepare the output file
        File file = new File(filename);
        Result result = new StreamResult(file);

        // Write the DOM document to the file
        Transformer xformer = TransformerFactory.newInstance()
                .newTransformer();
        xformer.transform(source, result);
    } catch (TransformerConfigurationException e) {
    } catch (TransformerException e) {
    }
}

}

我不确定我的方法“traversingXML”是否正常工作。我现在的问题是,经过调整的XML结构(一个已删除)不会写入newdoc

我做错了什么?谢谢你的帮助。

祝你好运, 彼得

1 个答案:

答案 0 :(得分:1)

您不会将原始文档复制到newdoc;而是创建一个新的空XML文档。

相反,请尝试以下代码:

 ...
 final Element element = doc.getDocumentElement(); // original code up to here

 traversingXML(element); // delete the node

 writeXmlFile(doc, "LSA_SALES_EXPORT_1507_test_zero_qu_OUT.xml"); // save modified document