如何使用java在xml中追加新值?

时间:2010-10-25 10:32:26

标签: java xml

我有一个类似的字符串:

       String msg=
      <?xml version="1.0" encoding="UTF-8" standalone="no">
      <validateEmail>
      <emailid>abc@gmail.com</emailid>
      <instanceid>instance1</instanceid>
      <msgname>validatemsg</msgname>
      <taskid>task1</taskid>
      </validateEmail>

我如何将此字符串转换为xml文件并附加新节点。

谢谢

2 个答案:

答案 0 :(得分:3)

此代码将您的String转换为XML文档,添加一个新节点,然后将其打印为String,以便检查它是否正确。

public void xml() throws ParserConfigurationException, SAXException, IOException {
    String msg = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>";
    msg += "<validateEmail><emailid>abc@gmail.com</emailid><instanceid>instance1</instanceid>";
    msg += "<msgname>validatemsg</msgname><taskid>task1</taskid></validateEmail>";

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document doc = builder.parse(new ByteArrayInputStream(msg.getBytes()));

    Node newNode = doc.createElement("newnode");
    newNode.setTextContent("value");
    Node root = doc.getFirstChild();
    root.appendChild(newNode);

    try {
        DOMSource domSource = new DOMSource(doc);
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        System.out.println(writer.toString());
    } catch (TransformerException ex) {
        ex.printStackTrace();
    }
}

答案 1 :(得分:1)

首先创建一个表示XML的DOM(文档对象模型)对象。

byte[] xmlBytes = msg.getBytes("UTF-8");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream(xmlBytes));

然后您需要将新节点添加到其中:

Element newNode = doc.createElement("myNode");
newNode.setTextContent("contents of node");
Element root = doc.getDocumentElement(); // the <validateEmail>
root.appendChild(newNode);

如果我正确理解了这个问题,那么你想将它写入文件系统。

File outputFile = ...;
Source source = new DOMSource(doc);
Result result = new StreamResult(outputFile);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);