如何修改java中的xml标签特定值?

我是新手,在xml.i上使用了一个xml文件,如下所示:

 -  -  Is the color of the car black?  -  Is the color of the car black?  -  Is the news paper wallstreet?  -  fragrance odor Lavendor?  -  Is the baggage collector available    

从上面的xml我只想改变

  wallstreet? as WonderWorld. 

我该如何改变wallstreet? 作为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(); } } 

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

任何身体请帮助我…..

使用

if (child.getNodeName().equals("Ans") && child.getTextContent().equals("wallstreet?"))

作为你的条件。

我建议XPath使用更少的代码精确选择要编辑的内容:

 XPath xpath = XPathFactory.newInstance().newXPath(); Element e = (Element) xpath.evaluate("//Ans[. = 'wallstreet']", document, XPathConstant.NODE); if (e != null) e.setTextContent("Wonderland"); 

您没有检查节点的值是否为“wallstreet?” – 所以它只是改变每个第一个子节点。

 String str = child.getFirstChild( ).getNodeValue( ); if ( "wallstreet?".compareTo( str ) == 0 ) { child.getFirstChild( ).setNodeValue( "WonderWorld" ); System.out.println( "tag val modified success fuly" ); }