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"));
0

2 Answers 2

4

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"));
}
Sign up to request clarification or add additional context in comments.

Comments

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.