JohnIdol JohnIdol - 3 months ago 28
C# Question

How to build XmlNodes from XmlReader

I am parsing a big number of big files and after profiling my bottleneck is:

XmlDocument doc = new XmlDocument();
doc.Load(filename);


This approach was very handy because I could extract nodes like this:

XmlNodeList nodeList = doc.SelectNodes("myXPath");


I am switching to XmlReader, but When I find the element I need to extract I am stuck with regards to how to build a XmlNode from it as not too familiar with XmlReader:

XmlReader xmlReader = XmlReader.Create(fileName);

while (xmlReader.Read())
{
//keep reading until we see my element
if (xmlReader.Name.Equals("myElementName") && (xmlReader.NodeType == XmlNodeType.Element))
{
// How do I get the Xml element from the reader here?
}
}


I'd like to be able to build a
List<XmlNode>
object. I am on .NET 2.0.

Any help appreciated!

Answer

The XmlNode type does not have a public constructor, so you cannot create them on your own. You will need to have an XmlDocument that you can use to create them:

XmlDocument doc = new XmlDocument();
while (xmlReader.Read())
{
    //keep reading until we see my element
    if (xmlReader.Name.Equals("myElementName") && (xmlReader.NodeType == XmlNodeType.Element))
    {
        // How do I get the Xml element from the reader here?
        XmlNode myNode = doc.CreateNode(XmlNodeType.Element, xmlReader.Name, "");
        nodeList.Add(myNode);
    }        
}
Comments