gpt4 book ai didi

java - 使用Java获取XML中标签的属性值

转载 作者:行者123 更新时间:2023-12-02 11:47:22 27 4
gpt4 key购买 nike

我正在尝试用 Java 将 text2 替换为其他内容。我在使用此代码时遇到问题:

try {
String filepath = "c:\\path\\file.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
Node a = doc.getFirstChild();
Node b = doc.getElementsByTagName("b").item(0);
NodeList list = b.getChildNodes();

for (int i = 0; i < list.getLength(); i++) {

Node node = list.item(i);
if ("c".equals(node.getNodeName())) { //Want to add '&& attribute value of key is 4'
node.setTextContent("new text");
}

}

// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);

System.out.println("Done");

} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}

XML 如下所示:

<?xml version="1.0" encoding="utf-8">
<a>
<b id="1">
<c key="3">text1</c>
<c key="4">text2</c> //Replace this
</b>
<b id="2">
<c key="5">text3</c>
<c key="6">text4</c>
</b>
</a>

我从这里的指南中得到了这个:https://www.mkyong.com/java/how-to-modify-xml-file-in-java-dom-parser/并且目前也在这一行给我一个错误 transformer.transform(source, result);

最佳答案

对于像这样简单的事情,您可以使用 XPath,并使用表达式 "//c[@key='4']" ,这意味着:查找 <c>具有名为 key 的属性的任何级别的元素值为4 .

Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse("file.xml");

Node c4 = (Node) XPathFactory.newInstance()
.newXPath()
.evaluate("//c[@key='4']", doc, XPathConstants.NODE);
c4.setTextContent("new text");

TransformerFactory.newInstance()
.newTransformer()
.transform(new DOMSource(doc),
new StreamResult(System.out));

输出

<?xml version="1.0" encoding="utf-8" standalone="no"?><a>
<b id="1">
<c key="3">text1</c>
<c key="4">new text</c>
</b>
<b id="2">
<c key="5">text3</c>
<c key="6">text4</c>
</b>
</a>

关于java - 使用Java获取XML中标签的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48106397/

27 4 0