【发布时间】:2013-05-10 20:05:59
【问题描述】:
到目前为止,这是我的代码:
// 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 进行硬编码。 请任何将不胜感激!
【问题讨论】:
-
还有人会碰巧知道如何部分更改节点值和属性值吗?意思是,给定搜索词“Gates”,它可以在两个地方找到,一个是节点值,另一个是属性值。我将如何更改它,以便仅用用户输入替换 Gates 这个词?