Search code examples
c#xmldocument

How to add a string as a node to a new XmlDocument?


Apologies for the very basic question, but I am trying to add a dynamically generated string into a new XmlDocument.

I've tried the below code initially, but wasn't sure if there was a better way.

var summaryXml = new XmlDocument();
    summaryXml.InnerXml.Replace("", "<Summary rev=\"" + newRevNumber + "\"></Summary>");

newRevNumber is just a MD5 hash of the current dateTime.

I have a collection of XML nodes that already have data, and I was trying to append them to the end of this new XmlDocument, after I've inserted the string listed above as the first child.

Also, I would have just gone with XDocument, but I'm not familiar enough with LINQ to XML to achieve results.


Solution

  • Also, I would have just gone with XDocument, but I'm not familiar enough with LINQ to XML to achieve results.

    LINQ to XML is super simple, and very lightweight compared to the very verbose API of XmlDocument.

    You can get the desired XML document as an XDocument like this:

    XDocument summaryXml = new XDocument(
        new XElement("Summary",
            new XAttribute("rev", newRevNumber)
        )
    );
    

    That produces the same document as the following XmlDocument usage:

    XmlDocument summaryXml = new XmlDocument();
    XmlElement summary = summaryXml.CreateElement("Summary");
    XmlAttribute rev = summaryXml.CreateAttribute("rev");
    rev.Value = newRevNumber;
    summary.Attributes.Append(rev);
    summaryXml.AppendChild(summary);
    

    As you can see, XDocument is a lot nicer… ;)

    If you need an XmlDocument though, you can always convert between the two formats as necessary. This question covers how to do that.