views:

222

answers:

2

I have deserialized an xml file into a C# object and have an "object" containing a specific node I have selected from this file.

I need to check if this node has child nodes. I do not know the specific type of the object at any given time.

At the moment I am just re-serializing the object into a string, and loading it into an XmlDocument before checking the HasChildNodes property, however when I have thousands of nodes to check this is extremely resource intensive and slow.

Can anyone think of a better way I can check if the object I have contains child nodes?

Many thanks :)

+1  A: 

I guess you could reverse the process (looking at all public members/properties that aren't marked [XmlIgnore], aren't null, and don't have a public bool ShouldSerialize*() that returns false or any of the other patterns), but this seems a lot of work...

Marc Gravell
@Marc Gavel thanks for the answer, but yea I was looking for something quick and easy. If there's nothing like that then I guess I won't bother rewriting and just grin and bear it :)Cheers!
AndyC
+1  A: 

try using Linq2xml, it has a class called XElement (or XDocument) which are much easier to use then the XmlDocument. something like this:

XElement x = XElement.Load("myfile.xml");
if (x.Nodes.Count() > 0)
{
  // do whatever
}

much less code, much more slick, very readable. if you have the xml already as a string, you can replace the Load with the Parse function.

Ami