java 如何用新值替换 XML 标签之间的旧值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15214818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:53:04  来源:igfitidea点击:

How to replace old value between XML tags with new value

javaxmlsetattribute

提问by JoshMachine

I have to replace the oldValuein the date tag with the newValuein the below XML. I am using setAttributefunction 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.

我必须oldValuenewValue下面的 XML替换日期标记中的 。我正在使用setAttribute函数来做到这一点,但它似乎不起作用。如果我必须使用不同的函数来替换标签之间的文本,请告诉我。

myfile.xml

我的文件.xml

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

replace.java

替换.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.

通过大量的阅读/实验,我找到setAttribute()了替换这样的 XML 的工作。但是,这对我不起作用。



回答by Jayamohan

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

您需要setTextContent(String textContent)方法而不是setAttribute方法。

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

oldValueis the TextContentof <date>element, not attribute. Check hereto find what is attribute.

oldValueTextContent<date>元件,而不是属性。检查此处以查找什么是属性。

回答by Alex

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

如果你设置属性,你会改变节点根的属性,所以它会像<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

java,dom,xml中设置新节点值的问题使用jdom解析
动态设置值到xml