在Java中更改XML文件中的一个值的最佳方法是什么? [英] What is best way to change one value in XML files in Java?

查看:621
本文介绍了在Java中更改XML文件中的一个值的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML文件,我知道我需要更改其值的节点名称。

I have an XML file and I know the node name I need to change the value for.

nodename是ipAddress。

The nodename is ipAddress.

我可以使用JDOM,获取文档,获取节点并更改值和写它或者我可以编写一个XSLT文件。

I can use JDOM, get document, get node and change the value and write it or I can write an XSLT file.

代码更改值来自Java,所以我的问题是哪个选项更好? XML文件的大小可以不同。

The code changing value goes from Java, so my question is which option is better? The size of the XML file can be different.

另一个与XSLT相关的问题:是否可以编写一个XSLT文件,这样我就不会列出所有的节点在XML中但是如果node == ipAddress 只指定,那么获取新值,我将如何从Java应用XSLT转换?

Another XSLT-related question: Is it possible to write an XSLT file such that I will not be listing all nodes that are in XML but will just specify like if node == ipAddress, then take the new value, and how would I apply the XSLT transformation from Java?

谢谢。

推荐答案

您可以使用标准的org.w3c.dom API获取DOM。然后使用标准的javax.xml.xpath API获取节点。然后使用javax.xml.transform API将其写回。

You could use the standard org.w3c.dom APIs to get a DOM. Then get the node using the standard javax.xml.xpath APIs. And then use the javax.xml.transform APIs to write it back out.

类似于:

import java.io.File;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import org.w3c.dom.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Document document = dbf.newDocumentBuilder().parse(new File("input.xml"));

        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        XPathExpression expression = xpath.compile("//A/B[C/E/text()=13]");

        Node b13Node = (Node) expression.evaluate(document, XPathConstants.NODE);
        b13Node.getParentNode().removeChild(b13Node);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.transform(new DOMSource(document), new StreamResult(System.out));
    }
}

这篇关于在Java中更改XML文件中的一个值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆