How to replace old value between XML tags with new value

一个人想着一个人 提交于 2019-12-24 09:38:58

问题


I have to replace the oldValue in the date tag with the newValue in the below XML. I am using setAttribute function to do that but it doesn't seem to work. Please do let me know if I have to use a different function for replace text between tags.

myfile.xml

<?xml version="1.0" encoding="UTF-8" ?>  
<root>  
        <date>oldValue</date>  
</root>

replace.java

Document doc = builder.parse(new File("myFile.xml"));  
Element root = doc.getDocumentElement();  
System.out.println("Before");  
System.out.println("Using getElementByTagName date: " + root.getElementsByTagName("date").item(0).getTextContent());  
System.out.println("Using getAttribute        date: " + root.getAttribute("date"));
root.setAttribute("date", "newValue");  
System.out.println("After");  
System.out.println("Using getElementByTagName date: " + root.getElementsByTagName("date").item(0).getTextContent());  
System.out.println("Using getAttribute        date: " + root.getAttribute("date"));

Output:

**Before**  
 Using getElementByTagName date: oldValue  
 Using getAttribute        date:  
 **After**  
 Using getElementByTagName date: oldValue  
 Using getAttribute        date: test  

With the a lot of reading/experimentation, I have found setAttribute() works for replacing an XML like this. But, this doesn't work for me.



回答1:


You need setTextContent(String textContent) method and not setAttribute method.

root.getElementsByTagName("date").item(0).setTextContent("newValue");

oldValue is the TextContent of <date> element, not attribute. Check here to find what is attribute.




回答2:


If you set attribute you change attribute of node root, so it will be like <root attrName = "attrValue">

There are questions which can help you to find an answer.

Problems setting a new node value in java, dom, xml parsing
dynamically set value to xml using jdom



来源:https://stackoverflow.com/questions/15214818/how-to-replace-old-value-between-xml-tags-with-new-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!