开发者

how to append a new value in xml using java?

开发者 https://www.devze.com 2023-01-21 15:29 出处:网络
i have an String like: String msg= <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"> <validate开发者_Python百科Email>

i have an String like:

       String msg=
      <?xml version="1.0" encoding="UTF-8" standalone="no">
      <validate开发者_Python百科Email>
      <emailid>abc@gmail.com</emailid>
      <instanceid>instance1</instanceid>
      <msgname>validatemsg</msgname>
      <taskid>task1</taskid>
      </validateEmail>

how i am able to convert this string into an xml file and append a new node.

Thanks


This code converts your String into an XML document, adds a new node, then prints it out as a String so you can check that it looks correct.

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();
    }
}


Firstly create a DOM (document object model) object representing your XML.

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

Then you need to add your new node to it:

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

Then you want to write it to the filesystem, if I understand the question correctly.

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

精彩评论

暂无评论...
验证码 换一张
取 消