到目前为止,这是我的代码:
// locate the node(s)
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList)xpath.evaluate("//root[text()='input[1]']", doc, XPathConstants.NODESET);
// make the change
for (int idx = 0; idx < nodes.getLength(); idx++) {
nodes.item(idx).setTextContent(input[3]);
}
// save the result
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(new DOMSource(doc), new StreamResult(new File(outputFile)));
Input[1] 是我在 XML 中寻找的内容,而 input [3] 是它被替换的内容。
这是 XML:
<root>
<accounts>
<account name="Bill Gates">
<position>CEO</position>
<phoneNumber>123-485-1854</phoneNumber>
<notes>Runs the company</notes>
</account>
<account name="Service Account"/>
<account name="Burt Mackland">
<position>CFO</position>
<phoneNumber>345-415-4813</phoneNumber>
<notes>Great CFO</notes> </account>
<account name="Joe Smith">
<position>Accountant</position>
<reportsTo>Burt Mackland</reportsTo>
<phoneNumber>135-118-7815</phoneNumber>
<notes>Must have ID checked at all Gates</notes>
</account>
</accounts>
<departments>
<deparment name="Finance">
<employeeCount>2</employeeCount>
</deparment>
<department name="Human Resources">
<employeeCount>0</employeeCount>
</department>
<department name="Executive">
<employeeCount>2</employeeCount>
</department>
</departments>
</root>
用户可能不知道 XML 中的内容。所以我不能在代码中对 Xpath 进行硬编码。请任何将不胜感激!