[英]how to append a new value in xml using java?
i have an String like: 我有一个像这样的字符串:
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>
how i am able to convert this string into an xml file and append a new node. 我如何能够将此字符串转换为xml文件并附加一个新节点。
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. 此代码将您的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();
}
}
Firstly create a DOM (document object model) object representing your XML. 首先创建一个表示XML的DOM(文档对象模型)对象。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.