How can I add a attribute to Root node of my XmlDocument() in C#

3.6k views Asked by At

I already have a XmlDocument object in C#. Let's say the InnerXml looks like this;

<MyResponse>
  <ResponseType>
    <Id>8825</Id>
  </ResponseType>
</MyResponse>

How can I add a attribute which has the name as uuid and the value as 781283721381, e.g uuid="781283721381". So my Xml output would look like the following;

<MyResponse uuid="781283721381">
  <ResponseType>
    <Id>8825</Id>
  </ResponseType>
</MyResponse>
1

There are 1 answers

0
fejesjoco On BEST ANSWER
document.DocumentElement.Attributes.Append(document.CreateAttribute("uuid")).Value = "12345"

Yeah, XmlDocument is a bit hard to modify, that's part of the reason why XDocument was invented. But it's the easiest to use XML serialization and work on objects.