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

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 BEFORE

<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后

<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>

解决方法:

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

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>

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念