如何修改java中的xml标签特定值? [英] how to modify xml tag specific value in java?
本文介绍了如何修改java中的xml标签特定值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚接触xml.i使用了一个xml文件,如下所示:
i am new to work on xml.i have used an xml file as follows:
<?xml version="1.0" encoding="UTF-8" ?>
- <root>
- <key>
<Question>Is the color of the car</Question>
<Ans>black?</Ans>
</key>
- <key>
<Question>Is the color of the car</Question>
<Ans>black?</Ans>
</key>
- <key>
<Question>Is the news paper</Question>
<Ans>wallstreet?</Ans>
</key>
- <key>
<Question>fragrance odor</Question>
<Ans>Lavendor?</Ans>
</key>
- <key>
<Question>Is the baggage collector available</Question>
<Ans />
</key>
</root>
来自上面的xml我只想更改
from the above xml i would like to change only
<Ans>wallstreet?</Ans> as <Ans>WonderWorld</Ans>.
如何更改wallstreet?作为WonderWorld?通过我的java应用程序。
how can i change wallstreet? as WonderWorld? through my java application.
我编写的java方法如下所示:
i have written java method as shown below:
public void modifyNodeval(){
try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File(path));
Node nodes1 = doc.getElementsByTagName("*");
for(int j=0;j<nodes1.getLength();j++)
{
//Get the staff element by tag name directly
Node nodes = doc.getElementsByTagName("key").item(j);
//loop the staff child node
NodeList list = nodes.getChildNodes();
for (int i = 0; i != list.getLength(); ++i)
{
Node child = list.item(i);
if (child.getNodeName().equals("Ans")) {
child.getFirstChild().setNodeValue("WonderWorld") ;
System.out.println("tag val modified success fuly");
}
}
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(path);
transformer.transform(source, result);
}
catch (Exception e)
{
e.printStackTrace();
}
}
使用上面的代码我可以更改全部标记文本作为奇迹世界,但我的意图是我想改变只有wallstreet?作为WonderWorld。
by using above code i am able to change the all tag text as wonder world but my intention is i want change only wallstreet? as WonderWorld.
任何身体请帮帮我.....
any body please help me.....
推荐答案
使用
if(child.getNodeName()。equals(Ans)&& child.getTextContent()。equals (wallstreet?))
作为你的if条件。
这篇关于如何修改java中的xml标签特定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文