gpt4 book ai didi

java - 用Java替换XML文件中的数据

转载 作者:行者123 更新时间:2023-12-01 05:24:55 24 4
gpt4 key购买 nike

我正在尝试替换

<photo>dummy.jpg</photo>

有了这个

<photo>NewImage_2012-03-22:15.00.00.jpg</photo>

代码如下所示

Element nameElement = (Element) fstNode;
NodeList nameElemList = nameElement.getElementsByTagName("photo");
Element firstElement = (Element) nameElemList.item(0);
NodeList fstNm = firstElement.getChildNodes();
Text newData = doc.createTextNode("NewImage_2012-03-22:15.00.00.jpg");
firstElement.replaceChild(newData, fstNm.item(0));
System.out.println("Data : " +
firstElement.getChildNodes().item(0).getNodeValue());

在输出中,它会打印新的照片名称,但不会替换 xml 文件中的数据。我错过了什么?

谢谢。

最佳答案

使用DocumentTraversal、NodeIterator来替换字符串。

 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse("/home/riddhish/developerworkspace/SplitString/src/com/updatexmlwithjava/file.xml");
DocumentTraversal traversal = (DocumentTraversal) doc;
Node a = doc.getDocumentElement();
System.out.println("Chield node length ="+a.getChildNodes().getLength());
NodeIterator iterator = traversal.createNodeIterator(a, NodeFilter.SHOW_ELEMENT, null, true);
Element b = null;
for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
Element e = (Element) n;
if ("parent tag".equals(e.getTagName())) {
System.out.println(""+e.getTagName() +" "+ e.getTextContent());
b = e;
} else if ("photo".equals(e.getTagName()) && "dummy.jpg".equals(e.getTextContent()) && b != null) {
e.setTextContent("NewImage_2012-03-22:15.00.00.jpg");
//a.removeChild(b);
}
}

关于java - 用Java替换XML文件中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9821943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com