java 修改xml某个值,在Java中更改XML文件中的一个值的最佳方法是什么?

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

The nodename is ipAddress.

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

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

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?

Thank you.

解决方案

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.

Something like:

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

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值