Vk Suhagiya
Vk Suhagiya

Reputation: 353

How can I change value of XML element based on another element in java?

currently I am working on XML modify task in my project for that I want to change xml element from source code below is my XML:

<Client_list>
       <Description>
             <ip>192.168.11.206</ip>
             <name>vishal suhagiya</name>
       </Description>
       <Description>
             <ip>192.168.11.205</ip>
             <name>kinnari jasoliya</name>
       </Description>
</Client_list>

I wrote in java like:

for (int i = 0; i < nodes.getLength(); i++) {
  Element Description = (Element)nodes.item(i);
                  Node element = nodes.item(i);


  Element ip = (Element)Description.getElementsByTagName("ip_address").item(0);
  String pName = ip.getTextContent();

  String Client = jTextField4.getText();

  if (pName.equals(Client)) {

      if("Name".equals(element.getNodeName()))
      {
          element.setTextContent(jTextField4.getText());
      }

  }

I need that if I want to change name of 192.168.11.205's then how can I change? So how can I change name in XML based on ip address

Upvotes: 0

Views: 211

Answers (2)

Michael Kay
Michael Kay

Reputation: 163282

Do the whole thing in XSLT.

<xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:param name="ip"/>
  <xsl:param name="newName"/>

  <xsl:template match="*">
    <xsl:copy><xsl:apply-templates/></xsl:copy>
  </xsl:template>

  <xsl:template match="name[../ip=$ip]">
    <name><xsl:value-of select="$newName"/></name>
  </xsl:template>
</xsl:transform>

Upvotes: 1

minus
minus

Reputation: 2786

I use xpath to manage this kind of updates.

    XPath xpath = XPathFactory.newInstance().newXPath();

    try {
        NodeList nodes = (NodeList) xpath.evaluate("//Description[ip='192.168.11.205']/name", doc, XPathConstants.NODESET);
        for(int i=0;i<nodes.getLength();i++){
            Element nameElement = (Element) nodes.item(i);
            nameElement.setTextContent("NewValue");
        }
    } catch (XPathExpressionException e) {
        // Some error management here
    }

If you need to manage XML documents as java objects you may want to have a look at a JAXB tutorial.

Upvotes: 1

Related Questions