gpt4 book ai didi

java - 在java中的XML中设置属性/节点

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

这是我的 XML:

<root>
<A id='1'>
<B>Blah</B>
<C>Test</C>
</A>
</root>

我想在下面添加,所以我的最终 XML 如下:

<root>
<A id='1'>
<B>Blah</B>
<C>Test</C>
<D>New value</D>
</A>
</root>

我可以使用 //A 在 XPath 中获取节点,但我不确定获取节点后如何添加或编辑值。

最佳答案

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
StringReader xml = new StringReader("<root><A id='1'><B>Blah</B><C>Test</C></A></root>");
Document doc = db.parse(new InputSource(xml));
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//A");
Element element = doc.createElement("D");
element.setTextContent("new value");
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
for(int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
node.appendChild(element);
}

关于java - 在java中的XML中设置属性/节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7917514/

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