Question

When I try and update a value in my XML document, instead of editing the existing value, it keeps inserting a new node with my new values.

If have tried this two ways with the same results...

var doc = XDocument.Parse(xmlString);

XElement shippingElement = (from xml2 in doc
  .Elements("extradata").Elements("SharedCustomAppData")
  .Elements("clsNameValues").Elements("clsnamevalue")
where xml2.Element("name").Attribute("Value").Value == "SHOP_FLOOR_INSTR"
select xml2).FirstOrDefault();

shippingElement.Element("value").Attribute("Value").Value = "Changed!";

And

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(oLine.ExtraData);
XmlNodeList nodes = xmlDoc.SelectNodes(
   "extradata/SharedCustomAppData/clsNameValues/clsnamevalue");

foreach (XmlNode node in nodes)
{
XmlNode nameNode = node.SelectSingleNode("name");

if (nameNode != null && nameNode.Attributes["Value"].Value == "SHOP_FLOOR_INSTR")
{
    XmlNode valueNode = node.SelectSingleNode("value");

    if (valueNode != null)
    {
        valueNode.Attributes["Value"].Value = line.SHOP_FLOOR_INSTR;
    }
}
}

The section of XML I'm trying to update looks like this:

  <SharedCustomAppData>
   <clsNameValues>
     <clsnamevalue>
       <name Value="SHOP_FLOOR_INSTR" />
       <value Value="Current value" />
     </clsnamevalue>
   </clsNameValues>
 </SharedCustomAppData>

No correct solution

OTHER TIPS

Shouldn't the element name be "name" not "value" in the assignment statement?

try this:

var doc = XDocument.Parse(xmlString);

XElement shippingElement = (from xml2 in doc
   .Elements("extradata").Elements("SharedCustomAppData")
   .Elements("clsNameValues").Elements("clsnamevalue")
where xml2.Element("name").Attribute("Value").Value == "SHOP_FLOOR_INSTR"
select xml2).FirstOrDefault();

shippingElement.Element("name").Attribute("Value").Value = "Changed!";

You can use System.Xml.XPath extensions for Linq to Xml (I believe code will look shorter):

var expression = "//extradata/SharedCustomAppData/clsNameValues/clsnamevalue[name/@Value='SHOP_FLOOR_INSTR']/value";
XElement valueElement = xdoc.XPathSelectElement(expression);
if (valueElement != null)
    valueElement.SetAttributeValue("Value", "Changed!");

Also be careful with namespaces (it's not clear from your sample xml if there is some namespace declared on parent node).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top