如何根据java中的值删除无界的xml节点

时间:2015-11-27 08:23:18

标签: java xml

我在尝试取消节点时遇到问题"在任何节点无界"的情况下。但是我正在研究的java代码是使第一个发生的节点无效,它应该根据事件/或节点内的数据(我们从variable2传递)使节点无效。 所以我需要你的帮助。

注意:代码不应包含任何静态信息。

INPUT1:

<urn:Library xmlns:urn="urn:sap-com:document:sap:idoc" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<urn:books>
    <urn:booksHeader>
        <urn:book>  <!-- occurrence 1 -->
            <urn:id>1</urn:id>
            <urn:name>name1</urn:name>
            <urn:author>author1</urn:author>
            <urn:price>700</urn:price>
            <urn:category>category1</urn:category>
        </urn:book>
        <urn:book>  <!-- occurrence 2 -->
            <urn:id>2</urn:id>
            <urn:name>name2</urn:name>
            <urn:author>author2</urn:author>
            <urn:price>700</urn:price>
            <urn:category>category2</urn:category>
        </urn:book>
        <urn:book>  <!-- occurrence 3 -->
            <urn:id>3</urn:id>
            <urn:name>name3</urn:name>
            <urn:author>author3</urn:author>
            <urn:price>7007</urn:price>
            <urn:category>category3</urn:category>
        </urn:book>
        <urn:book>  <!-- occurrence 4 -->
            <urn:id>4</urn:id>
            <urn:name>name4</urn:name>
            <urn:author>author4</urn:author>
            <urn:price>40000</urn:price>
            <urn:category>category4</urn:category>
        </urn:book>
        <urn:book>  <!-- occurrence 5 -->
            <urn:id>5</urn:id>
            <urn:name>name5</urn:name>
            <urn:author>author5</urn:author>
            <urn:price>500</urn:price>
            <urn:category>category5</urn:category>
        </urn:book>
    </urn:booksHeader>
</urn:books>

input2:

<err:ErrorNodes xmlns:err="http://www.example.org/ErrorNodes"> 
<err:ErrorNode>
    <urn:author xmlns:urn="urn:sap-com:document:sap:idoc">author3</urn:author>
    <urn:price xmlns:urn="urn:sap-com:document:sap:idoc">40000</urn:price>
</err:ErrorNode>

下面是我正在处理的java代码

java代码:

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.StringWriter;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

public class XMLMergeUtilIDOC {
public static void main(String[] aa) throws Exception {
    String strInputXml = "Pass input1 here";

    String strErrorXml ="Pass input2 here";


    System.out.println("Hello"+mergeIDOCData(strInputXml,strErrorXml));
}

public static String mergeIDOCData(String strInputXml,
                                   String strErrorXml) throws    Exception,                                                                 SAXException,
                                                                 IOException {
    Document inputDocument =
        loadXMLFrom(new ByteArrayInputStream(strInputXml.getBytes()));

    Document errorDocument =
        loadXMLFrom(new ByteArrayInputStream(strErrorXml.getBytes()));


    String strOutputXml =
        convertDomToString(mergeIDOCData(inputDocument, errorDocument).getOwnerDocument());


    return strOutputXml;
}

public static Node mergeIDOCData(Document inputDocument,
                                 Document errorDocument) throws Exception {
    String strIdocNs = "urn:sap-com:document:sap:idoc";


    XPath xpathError = XPathFactory.newInstance().newXPath();
    UniversalNamespaceCache nsError =
        new UniversalNamespaceCache(errorDocument, false);


    xpathError.setNamespaceContext(nsError);


    XPath xpathInput = XPathFactory.newInstance().newXPath();
    UniversalNamespaceCache nsInputDoc =
        new UniversalNamespaceCache(inputDocument, false);

    xpathInput.setNamespaceContext(nsInputDoc);


    String xpathExpression =
        "//" + nsError.getPrefix("http://www.example.org/ErrorNodes") +
        ":ErrorNode";


    Node node =
        (Node)xpathError.evaluate(xpathExpression, errorDocument, XPathConstants.NODE);
    if (node != null) {
        NodeList nodes = node.getChildNodes();
        int j = nodes.getLength();
        for (int i = 0; i < j; i++) {
            String errorNodeName = nodes.item(i).getNodeName();

            String errorNodevalue = nodes.item(i).getTextContent();
            System.out.println("--->>>>" + errorNodevalue);

            if ((errorNodeName == null) ||
                (!errorNodeName.trim().equals("#text"))) {
                if (errorNodeName != null) {
                    errorNodeName =
                            errorNodeName.replaceAll(nsError.getPrefix(strIdocNs),
                                                     nsInputDoc.getPrefix(strIdocNs));

                    System.out.println("error node name - " +
                                       errorNodeName);

                    try {

                        (inputDocument.getElementsByTagName(errorNodeName).item(0)).getFirstChild().setNodeValue("");

                    } catch (Exception ex) {
                        System.out.println(" Error Node Replacement " +
                                           ex.getMessage());
                    }
                }
            }
        }
    }
    return inputDocument.getDocumentElement();
}

public static Node mergeIDOCData(Node inputNode,
                                 Node errorNode) throws Exception {
    Node newDocument =
        mergeIDOCData(inputNode.getOwnerDocument(), errorNode.getOwnerDocument());

    return newDocument;
}

public static Document loadXMLFrom(InputStream is) throws SAXException,
                                                          IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        System.out.println(" Prase Configuration Error :: " +
                           ex.getMessage());
    }
    Document doc = builder.parse(is);
    is.close();
    return doc;
}

private static String convertDomToString(Document doc) throws Exception {
    Transformer transformer =
        TransformerFactory.newInstance().newTransformer();

    transformer.setOutputProperty("indent", "yes");
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);
    String xmlString = sw.toString();
    return xmlString;
}

public static class UniversalNamespaceCache implements NamespaceContext {
    private static final String DEFAULT_NS = "DEFAULT";
    private Map<String, String> prefix2Uri = new HashMap();
    private Map<String, String> uri2Prefix = new HashMap();

    public UniversalNamespaceCache(Document document,
                                   boolean toplevelOnly) {
        examineNode(document.getFirstChild(), toplevelOnly);
        System.out.println("The list of the cached namespaces:");
        for (String key : this.prefix2Uri.keySet()) {
            System.out.println("prefix " + key + ": uri " +
                               (String)this.prefix2Uri.get(key));
        }
    }

    private void examineNode(Node node, boolean attributesOnly) {
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            storeAttribute((Attr)attribute);
        }
        if (!attributesOnly) {
            NodeList chields = node.getChildNodes();
            for (int i = 0; i < chields.getLength(); i++) {
                Node chield = chields.item(i);
                if (chield.getNodeType() == 1) {
                    examineNode(chield, false);
                }
            }
        }
    }

    private void storeAttribute(Attr attribute) {
        if ((attribute.getNamespaceURI() != null) &&
            (attribute.getNamespaceURI().equals("http://www.w3.org/2000/xmlns/"))) {
            if (attribute.getNodeName().equals("xmlns")) {
                putInCache("DEFAULT", attribute.getNodeValue());
            } else {
                putInCache(attribute.getLocalName(),
                           attribute.getNodeValue());
            }
        }
    }

    private void putInCache(String prefix, String uri) {
        this.prefix2Uri.put(prefix, uri);
        this.uri2Prefix.put(uri, prefix);
    }

    public String getNamespaceURI(String prefix) {
        if ((prefix == null) || (prefix.equals(""))) {
            return (String)this.prefix2Uri.get("DEFAULT");
        }
        return (String)this.prefix2Uri.get(prefix);
    }

    public String getPrefix(String namespaceURI) {
        return (String)this.uri2Prefix.get(namespaceURI);
    }

    public Iterator getPrefixes(String namespaceURI) {
        return null;
    }
}

}

目前如果我运行下面的java代码是输出:

<urn:Library xmlns:urn="urn:sap-com:document:sap:idoc" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<urn:books>
    <urn:booksHeader>
        <urn:book>
            <urn:id>1</urn:id>
            <urn:name>name1</urn:name>
            <urn:author/>                 <!-- **Wrongly nullified**-->
            <urn:price/>                  <!-- **Wrongly nullified**-->
            <urn:category>category1</urn:category>
        </urn:book>
        <urn:book>
            <urn:id>2</urn:id>
            <urn:name>name2</urn:name>
            <urn:author>author2</urn:author>
            <urn:price>700</urn:price>
            <urn:category>category2</urn:category>
        </urn:book>
        <urn:book>
            <urn:id>3</urn:id>
            <urn:name>name3</urn:name>
            <urn:author>author3</urn:author>
            <urn:price>7007</urn:price>
            <urn:category>category3</urn:category>
        </urn:book>
        <urn:book>
            <urn:id>4</urn:id>
            <urn:name>name4</urn:name>
            <urn:author>author4</urn:author>
            <urn:price>40000</urn:price>
            <urn:category>category4</urn:category>
        </urn:book>
        <urn:book>
            <urn:id>5</urn:id>
            <urn:name>name5</urn:name>
            <urn:author>author5</urn:author>
            <urn:price>500</urn:price>
            <urn:category>category5</urn:category>
        </urn:book>
    </urn:booksHeader>
</urn:books>

预期产出:

<urn:Library xmlns:urn="urn:sap-com:document:sap:idoc" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<urn:books>
    <urn:booksHeader>
        <urn:book>
            <urn:id>1</urn:id>
            <urn:name>name1</urn:name>
            <urn:author>author1</urn:author>
            <urn:price>700</urn:price>
            <urn:category>category1</urn:category>
        </urn:book>
        <urn:book>
            <urn:id>2</urn:id>
            <urn:name>name2</urn:name>
            <urn:author>author2</urn:author>
            <urn:price>700</urn:price>
            <urn:category>category2</urn:category>
        </urn:book>
        <urn:book>
            <urn:id>3</urn:id>
            <urn:name>name3</urn:name>
            <urn:author/>         <!-- **should nullify**-->
            <urn:price>7007</urn:price>
            <urn:category>category3</urn:category>
        </urn:book>
        <urn:book>
            <urn:id>4</urn:id>
            <urn:name>name4</urn:name>
            <urn:author>author4</urn:author>
            <urn:price/>           <!-- **should nullify**-->
            <urn:category>category4</urn:category>
        </urn:book>
        <urn:book>
            <urn:id>5</urn:id>
            <urn:name>name5</urn:name>
            <urn:author>author5</urn:author>
            <urn:price>500</urn:price>
            <urn:category>category5</urn:category>
        </urn:book>
    </urn:booksHeader>
</urn:books>

0 个答案:

没有答案