如何在Java中修改xml标记的特定值?

我是xml.i的新手,我使用了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>.

我该如何更改walltreet?作为WonderWorld?通过我的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();

}

}

通过使用上面的代码,我能够将所有标签文本更改为奇迹世界,但是我的意图是我只想更改walltreet?作为WonderWorld。

任何人请帮助我.....

回答:

if (child.getNodeName().equals("Ans") &&

child.getTextContent().equals("wallstreet?"))

作为您的条件。

以上是 如何在Java中修改xml标记的特定值? 的全部内容, 来源链接: utcz.com/qa/404785.html

回到顶部