6

Looking to add an attribute to an existing xml element <D_COMMS>, not replace the existing attribute just add it to the beginning.

This is the XML

<OUTPUT version="2.0">
 <RESPONSE>
  <DATA id="17fb13cca6c5463597fdf340c044069f">
    <![CDATA[<ID> jdfkldklfjdkl</ID><D_COMMS>ON this date...</D_COMMS>]]>
  </DATA>
 </RESPONSE>

This XML is the result of a HTTPWebResponse so this is what the XMl looks like when it comes back to me and I need to add a value to the D_COMMS element and send it back.Tried something like this to look for the descendant DATA and add it that way.

var addelement = doc.Descendants("DATA").First();
addelement.Add(XElement("D_COMMS","On this date we said"));
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Jt2ouan
  • 1,964
  • 9
  • 33
  • 55

2 Answers2

4

A better one to set attribute is in here Adding attributes to an XML node

    XmlElement id = doc.CreateElement("id");
    id.SetAttribute("userName", "Tushar");
Community
  • 1
  • 1
FJ Chen
  • 41
  • 1
3

You can find the DATA node and add an attribute as follows:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList dataNodes = doc.GetElementsByTagName("DATA");
if (dataNodes != null && dataNodes.Count > 1)
{
    dataNodes[0].Attributes.Append(doc.CreateAttribute("D_COMMS", "On this date we said"));
}
jam40jeff
  • 2,576
  • 16
  • 14