更新XML字符串

时间:2013-12-03 14:56:31

标签: java xml dom xml-parsing

从给定的XML String中,我必须更新End Date值。 即使我在updateNodeValue()方法中更新xml,我的最终输出xml也与输入xml相同。

有人可以告诉我这段代码中的错误

import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
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;
import org.xml.sax.InputSource;


public class MyClass{

    static String strXml = "<INFO><BeginDate>2013-12-02</BeginDate><EndDate>2014-01-31</EndDate></INFO>";

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

        System.out.println(strXml);
        Document doc = StringToDocument(strXml);
        updateNodeValue(doc);
        String newxml = DocumentToString(doc);
        System.out.println(newxml);

    }

    public static void updateNodeValue(Document doc) {

        Node rootNode = doc.getFirstChild();
        NodeList list = rootNode.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {

            Element element = (Element) list.item(i);
            Node node = list.item(i);
            if ("EndDate".equals(node.getNodeName())) {
                element.setNodeValue("2013-12-12");
                return;
            }
        }
    }

    public static String DocumentToString(Document doc) throws Exception {

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        String output = writer.getBuffer().toString();
        return output;
    }

    public static Document StringToDocument(String strXml) throws Exception {

        Document doc = null;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            StringReader strReader = new StringReader(strXml);
            InputSource is = new InputSource(strReader);
            doc = (Document) builder.parse(is);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

        return doc;
    }
}

2 个答案:

答案 0 :(得分:2)

element.setTextContent(...)方法中使用updateNodeValue

答案 1 :(得分:1)

您应该使用的方法不是setNodeValue(),而是setTextContent()

请参阅http://docs.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Node.html#setNodeValue(java.lang.String)