简体   繁体   中英

Java DOM: cannot write adapted XML to file

I have the following simplified 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>

I need to delete each complete <R> element if the <productQuantityinttrue> element equals "0".

I came up with the following Java code:

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) {
    }
}

}

I am not sure if my method "traversingXML" is working properly. My problem right now is that the adapted XML structure (one deleted) is not written to newdoc .

What am I doing wrong? Thank you for your help.

Best regards, Peter

You don't copy the original document to newdoc ; instead you create a new, empty XML document.

Instead, try this code:

 ...
 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM