Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is instantiating XmlDocument expensive?

Tags:

c#

.net

xml

I have the following function:

public static XmlNode GetXMLNodeFromString(string strXML)
{
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(strXML);
    return doc.DocumentElement;
}

which can be called a million times in a line of code that gets returned from a database call:

while (reader.Read())
{
    myXMLList.Add(GetXMLNodeFromString((string)reader["GMLString"]));
}

Is there a better way than to keep instantiating the xmlDocument for every row? Or is it fine to do so?

I don't want to this:

XmlDocument doc = new XmlDocument();
while (reader.Read())
{
    myXMLList.Add(doc, GetXMLNodeFromString((string)reader["GMLString"]));
}

because in all reality there is a tree of functions that i would have to add it to. Not just GetXMLNodeFromString.

Can i do something like this:

public static class Common
{
    public static XmlDocument doc = new XmlDocument();
    public static XmlNode GetXMLNodeFromString(string strXML)
    {
        doc.LoadXml(strXML);
        return doc.DocumentElement;
    }
}

What should i do?

like image 225
capdragon Avatar asked Jun 06 '26 10:06

capdragon


2 Answers

I recommend XmlReader if you're having performance problems, as it allows you to parse the XML as it comes in, rather than pre-parsing it and creating an in-memory object model that you're going to have to go back through again anyway. It can require restructuring your code a bit, however, as it gives you sequential (as opposed to random) access. If you don't need random access, it's a good choice.

like image 194
Dan Bryant Avatar answered Jun 09 '26 00:06

Dan Bryant


We have found XmlDocument sluggish, but only because we're thrashing it beyond the scope of its design. Instantiating one for every table row however will cause you massive problems. It's a heavyweight class designed for in-place manipulation - which it is very good at - and if you're creating and destroying them faster than a human being could count in their head, you're overworking it.

like image 34
Tom W Avatar answered Jun 08 '26 22:06

Tom W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!