Tuesday, March 1, 2011

How do I create an xmlElement from the current node of a xmlReader?

If I have an xmlreader instance how can I use it to read its current node and end up with a xmlElement instance?

From stackoverflow
  • Not tested, but how about via an XmlDocument:

        XmlDocument doc = new XmlDocument();
        doc.Load(reader);
        XmlElement el = doc.DocumentElement;
    

    Alternatively (from the cmoment), something like:

        doc.LoadXml(reader.ReadOuterXml());
    

    But actually I'm not a fan of that... it forces an additional xml-parse step (one of the more CPU-expensive operations) for no good reason. If the original is being glitchy, then perhaps consider a sub-reader:

        using (XmlReader subReader = reader.ReadSubtree())
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(subReader);
            XmlElement el = doc.DocumentElement;
        }
    
    TheDeeno : change line 2 to doc.LoadXml(reader.ReadOuterXml()); so I can accept. Thanks.
    Sunny : How this answers the question? This will read the whole xml into XmlDocument, and will return the root element only.
    Marc Gravell : @Sunny; the root element contains all other elements as descendants
  • Assuming that you have XmlDocument, where you need to attach the newly created XmlElement:

    XmlElement myElement;
    myXmlReader.Read();
    if (myXmlReader.NodeType == XmlNodeType.Element)
    {
       myElement = doc.CreateElement(myXmlReader.Name);
       myElement.InnerXml = myXmlReader.InnerXml;
    }
    

    From the docs: Do not instantiate an XmlElement directly; instead, use methods such as CreateElement.

0 comments:

Post a Comment