如何使用XMLBeans XmlObject将节点添加到XML [英] How to add a node to XML with XMLBeans XmlObject

查看:103
本文介绍了如何使用XMLBeans XmlObject将节点添加到XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是获取一个XML字符串,并使用XMLBeans XmlObject对其进行解析,并添加一些子节点.

My goal is to take an XML string and parse it with XMLBeans XmlObject and add a few child nodes.

这是一个示例文档(xmlString),

Here's an example document (xmlString),

<?xml version="1.0"?>
<rootNode>
 <person>
  <emailAddress>joefoo@example.com</emailAddress>
 </person>
</rootNode>

这是添加一些节点后我希望XML文档成为的方式,

Here's the way I'd like the XML document to be after adding some nodes,

<?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/>.

Basically, just adding the <phoneNumbers/> node with two child nodes <home/> and <work/>.

据我所知,

XmlObject xml = XmlObject.Factory.parse(xmlString);

谢谢

推荐答案

XMLBeans似乎很麻烦,这是使用 XOM :

XMLBeans seems like a hassle, here's a solution using XOM:

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

这篇关于如何使用XMLBeans XmlObject将节点添加到XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆