gpt4 book ai didi

java xml 检索命名参数

转载 作者:行者123 更新时间:2023-11-29 05:40:37 25 4
gpt4 key购买 nike

<root>
<program name="SomeProgramName">
<params>
<param name='name'>test</param>
<param name='name2'>test2</param>
</params>
</program>
</root>

我有上面的 xml 文档。我需要将 test 的值更改为新值

我在 xml 文档中读为

String xmlfile = "path\\to\\file.xml"
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlfile);

//get the params element
Node params = doc.getElementsByTagName("params").item(0);

//get a list of nodes in the params element
NodeList param = params.getChildNodes();

这就是我卡住的地方。我找不到通过“名称”设置参数元素之一的值的方法

我正在使用 java 1.7

最佳答案

您需要输入每个节点以输入 Element能够设置文本和属性。你可能想看看 XPath ,这简化了这样的事情。

import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;

public class Demo {

public static void main(String[] args) throws Exception {
String xmlfile = "src/forum17753835/file.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(xmlfile);

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
Element element = (Element) xpath.evaluate("/root/program/params/param[@name='name2']", doc, XPathConstants.NODE);
System.out.println(element.getTextContent());
}

}

关于java xml 检索命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17753835/

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