2013-03-05 49 views
1

我必须将date标记中的oldValue替换为下面的XML中的newValue。我正在使用setAttribute函数来做到这一点,但它似乎没有工作。如果必须使用不同的功能替换标签之间的文字,请告诉我。如何用新值替换XML标记之间的旧值

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

输出:

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

有了很多的REA丁/实验,我发现setAttribute()工程取代这样的XML。但是,这对我不起作用。


+1

打开和关闭XML标记之间的文本是* not *属性。这是内容。 – 2013-03-05 02:44:50

+0

@ Code-Guru你是对的。我混淆了内容的属性。 – JoshMachine 2013-03-05 02:56:02

回答

2

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

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

oldValue<date>元件的TextContent,不属性。检查here以查找属性。

+1

谢谢,这有很大的帮助。 – JoshMachine 2013-03-05 02:56:55

相关问题