如何使用Java中的xpath编辑/更新XML文件中的节点

时间:2011-06-28 19:04:42

标签: java xml xpath

Java代码:

public void update(String id) throws Exception
  {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(file_);
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();

    XPathExpression expr = xpath.compile("Servers/server[@ID=" + id + "]");
    Node nodeGettingChanged = (Node) expr.evaluate(doc, XPathConstants.NODE);

   //HELP START

           //? ? ? How do get the node/elements guts to alter that guy

   //HELP END

   TransformerFactory transformerFactory = TransformerFactory.newInstance();
   Transformer transformer = transformerFactory.newTransformer();
   DOMSource source = new DOMSource(doc);

   StreamResult result = new StreamResult(file_);
   transformer.transform(source, result);
  }

XML之前

<Servers>
    <server ID="12234">  // <-- I want to change this node
        <name>Greg</name>
        <ip>127.0.0.1</ip>
        <port>1897</port>
    </server>
    <server ID="42234">
        <name>Bob</name>
        <ip>127.0.0.1</ip>
        <port>1898</port>
    </server>
    <server ID="5634">
        <name>Tom</name>
        <ip>127.0.0.1</ip>
        <port>1497</port>
    </server>
</Servers>

XML AFTER

<Servers>
    <server ID="12234">  // <-- This guy is now changed
        <name>SomethingElse</name>
        <ip>localHost</ip>
        <port>4447</port>
    </server>
    <server ID="42234">
        <name>Bob</name>
        <ip>127.0.0.1</ip>
        <port>1898</port>
    </server>
    <server ID="5634">
        <name>Tom</name>
        <ip>127.0.0.1</ip>
        <port>1497</port>
    </server>
</Servers>

3 个答案:

答案 0 :(得分:4)

可能不是最有效的代码,但它有效(避免使用文本元素)。

NodeList childNodes = nodeGettingChanged.getChildNodes();
for (int i = 0; i != childNodes.getLength(); ++i)
{
    Node child = childNodes.item(i);
    if (!(child instanceof Element))
        continue;

    if (child.getNodeName().equals("name"))
        child.getFirstChild().setNodeValue("SomethingElse") ;
    else if (child.getNodeName().equals("ip"))
        child.getFirstChild().setNodeValue("localHost") ;
    else if (child.getNodeName().equals("port"))
        child.getFirstChild().setNodeValue("4447") ;
}

输出已更改的XML片段:

<server ID="12234">
    <name>SomethingElse</name>
    <ip>localHost</ip>
    <port>4447</port>
</server>

答案 1 :(得分:1)

你可以试试这个:

NodeList children = nodeGettingChanged.getChildNodes();
chidren.item(0).setNodeValue("SomethingElse");
chidren.item(1).setNodeValue("localHost");
chidren.item(2).setNodeValue("4447");

答案 2 :(得分:1)

查看Node#getFirstChild()Node#getNextSibling()来迭代子节点。还要记住,文本节点也存在于元素之间,如果你不想要它们,你必须忽略它们。