tags:

views:

1026

answers:

2

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

+1  A: 

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;
    }
Marc Gravell
change line 2 to doc.LoadXml(reader.ReadOuterXml()); so I can accept. Thanks.
TheDeeno
How this answers the question? This will read the whole xml into XmlDocument, and will return the root element only.
Sunny
@Sunny; the root element contains all other elements as descendants
Marc Gravell
+1  A: 

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.

Sunny