gpt4 book ai didi

java - 如何使用 XMLBeans XmlObject 向 XML 添加节点

转载 作者:数据小太阳 更新时间:2023-10-29 02:18:17 24 4
gpt4 key购买 nike

我的目标是获取一个 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);

谢谢

最佳答案

下面是一个使用 XmlCursor 插入新元素的例子。您还可以获得 XmlObject 的 DOM 节点并使用这些 API。

import org.apache.xmlbeans.*;

/**
* Adding nodes to xml using XmlCursor.
* @see http://xmlbeans.apache.org/docs/2.4.0/guide/conNavigatingXMLwithCursors.html
* @see http://xmlbeans.apache.org/docs/2.4.0/reference/org/apache/xmlbeans/XmlCursor.html
*/
public class AddNodes
{
public static final String xml =
"<rootNode>\n" +
" <person>\n" +
" <emailAddress>joefoo@example.com</emailAddress>\n" +
" </person>\n" +
"</rootNode>\n";

public static XmlOptions saveOptions = new XmlOptions().setSavePrettyPrint().setSavePrettyPrintIndent(2);

public static void main(String[] args) throws XmlException
{
XmlObject xobj = XmlObject.Factory.parse(xml);
XmlCursor cur = null;
try
{
cur = xobj.newCursor();
// We could use the convenient xobj.selectPath() or cur.selectPath()
// to position the cursor on the <person> element, but let's use the
// cursor's toChild() instead.
cur.toChild("rootNode");
cur.toChild("person");
// Move to </person> end element.
cur.toEndToken();
// Start a new <phoneNumbers> element
cur.beginElement("phoneNumbers");
// Start a new <work> element
cur.beginElement("work");
cur.insertChars("555-555-5555");
// Move past the </work> end element
cur.toNextToken();
// Or insert a new element the easy way in one step...
cur.insertElementWithText("home", "555-555-5555");
}
finally
{
if (cur != null) cur.dispose();
}

System.out.println(xobj.xmlText(saveOptions));
}

}

关于java - 如何使用 XMLBeans XmlObject 向 XML 添加节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2519804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com