Search code examples
c#xmlxmldocument

Create System.Xml.XmlDocument, not from string


It is possible to create a System.Xml.XmlDocument without initializing by parsing a string?
I want to create a XmlDocument representing the XML <rootEl />

I known the normal way to initialize an XmlDocument is by string-parsing as below:

System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml("<rootEl />");

However, is it possible to use the method outlined below?

System.Xml.XmlDocument doc = new System.Xml.XmlDocument("rootEl");    

(I understand System.Xml.Linq seems to be more flexible, but right now I am stuck with oldschool.)


Solution

  • Well, it's not possible to do it with exactly the code you've given. There's no constructor for XmlDocument which takes the content, either as a stream or as a string.

    On the other hand, you could write:

    XmlDocument doc = new XmlDocument();
    doc.AppendChild(doc.CreateElement("rootEl"));
    

    Is that what you want? Please be more specific about what you're trying to achieve.