微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。