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 fil
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));
}
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)