Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

xml

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

like image 437
Dane O'Connor Avatar asked Nov 12 '08 15:11

Dane O'Connor


People also ask

How to Read Xml element value in c# using XmlReader?

MoveToContent(); var data = reader. ReadElementContentAsString(); Console. WriteLine(data); In the example, we read the value from the simple XML document with XmlReader .

What does XmlReader create FS do?

Creates a new XmlReader instance using the specified stream with default settings. Creates a new XmlReader instance by using the specified URI and settings.

What is the difference between XDocument and XmlDocument?

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument .


1 Answers

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;
    }
like image 182
Marc Gravell Avatar answered Sep 28 '22 01:09

Marc Gravell