我的目标是获取XML字符串并使用XMLBeans XmlObject解析它并添加一些子节点.
这是一个示例文档(xmlString),
<?xml version="1.0"?>
<rootNode>
<person>
<emailAddress>joefoo@example.com</emailAddress>
</person>
</rootNode>
这是添加一些节点后我想要XML文档的方式,
<?xml version="1.0"?>
<rootNode>
<person>
<emailAddress>joefoo@example.com</emailAddress>
<phoneNumbers>
<home>555-555-5555</home>
<work>555-555-5555</work>
<phoneNumbers>
</person>
</rootNode>
基本上,只需添加< phoneNumbers />具有两个子节点的节点< home />和< work />.
就我而言,
XmlObject xml = XmlObject.Factory.parse(xmlString);
谢谢
解决方法:
import nu.xom.*;
Builder = new Builder();
Document doc = builder.build(new java.io.StringBufferInputStream(inputXml));
Nodes nodes = doc.query("person");
Element homePhone = new Element("home");
homePhone.addChild(new Text("555-555-5555"));
Element workPhone = new Element("work");
workPhone.addChild(new Text("555-555-5555"));
Element phoneNumbers = new Element("phoneNumbers");
phoneNumbers.addChild(homePhone);
phoneNumbers.addChild(workPhone);
nodes[0].addChild(phoneNumbers);
System.out.println(doc.toXML()); // should print modified xml