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
2008-11-12 16:01:30
change line 2 to doc.LoadXml(reader.ReadOuterXml()); so I can accept. Thanks.
TheDeeno
2008-11-12 16:37:42
How this answers the question? This will read the whole xml into XmlDocument, and will return the root element only.
Sunny
2008-11-12 16:56:41
@Sunny; the root element contains all other elements as descendants
Marc Gravell
2008-11-13 05:00:44
+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
2008-11-12 16:50:24