【发布时间】:2011-11-30 14:08:24
【问题描述】:
我是 xml 的新手。我使用的 xml 文件如下:
<?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我只想改变
<Ans>wallstreet?</Ans> as <Ans>WonderWorld</Ans>.
我怎样才能改变华尔街?作为奇迹世界?通过我的 java 应用程序。
我写的java方法如下:
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。
任何人请帮助我.....
【问题讨论】:
-
到目前为止您尝试过什么?你有一些代码给我们看吗?另外,如果接受更多答案,这里的人会更有帮助。
-
@forty-2 检查我的 java 代码