how to modify xml tag specific value in java?

后端 未结 3 509
深忆病人
深忆病人 2020-12-10 00:08

i am new to work on xml.i have used an xml file as follows:

 
      - 
      - 
              


        
相关标签:
3条回答
  • 2020-12-10 00:31

    You are not checking if the value of the node is "wallstreet?" - so it simply changes every first child node.

    String str = child.getFirstChild( ).getNodeValue( );
    if ( "wallstreet?".compareTo( str ) == 0 )
    {
        child.getFirstChild( ).setNodeValue( "WonderWorld" );
        System.out.println( "tag val modified success fuly" );
    }
    
    0 讨论(0)
  • 2020-12-10 00:33

    use

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

    as your if condition.

    0 讨论(0)
  • 2020-12-10 00:47

    I would recommend XPath to select exactly what you want to edit with a lot less code:

    XPath xpath = XPathFactory.newInstance().newXPath();
    Element e = (Element) xpath.evaluate("//Ans[. = 'wallstreet']", document, XPathConstant.NODE);
    if (e != null)
      e.setTextContent("Wonderland");
    
    0 讨论(0)
提交回复
热议问题