Quantcast
Viewing all articles
Browse latest Browse all 12583

Update XML element value or attribute value

Hello,

I have this Xml document and i just want to know how to update the element 'name' value based on target id:

<sites>
  <domain id="US1.COM">
    <site id="s1">     
      <target id="T1">
        <name>SVR1</name>
      </target>
      <target id="T2">
        <name>SVR2</name>
      </target>
      <target id="T3">
        <name>SVR3</name>
      </target>
      <target id="T4">
        <name>SVR4</name>
      </target>
      <target id="WKS1">
        <name></name>
      </target>
      <target id="WKS2">
        <name></name>
      </target>
    </site>
<sites>

I have a data entry WindowForm that user searches the site id and displays target id & its Name(s) on textbox.

When user make changes on name value and click on Update button, its should save/update the Xml document.

I tried this code and won't work..

var oSites = (from s in doc.Descendants("site")
               where s.Attribute("id").Value == ID.ToString()
               from t in s.Elements("target")
               select new cSites
               {
                   TargetId = (string)t.Attribute("id").Value,
                    Name = (string)t.Element("name").Value
                });

foreach (var csites in oSites)
{
              
   if (csites.TargetId.Equals("T1"))
   {
        XElement xelement1 = doc.XPathSelectElement("~/../target[@id='T1']/name");
        xelement1.Value = txtT1.Text.ToString();
   }
 
   if (csites.TargetId.Equals("T2"))
   {
        XElement xelement1 = doc.XPathSelectElement("~/../target[@id='T2']/name");
        xelement1.Value = txtT1.Text.ToString();
   }

   ...
}

doc.Save(FilePath);

 ...

Any suggestion or sample code to resolve updating the XML documents?

Thanks for your help.
Willie


Viewing all articles
Browse latest Browse all 12583

Trending Articles