tags:

views:

25

answers:

2

What is the more efficient way to check an XmlDocument for an XmlDeclaration node?

+1  A: 

What sort of "efficiency" are you after? Efficiency of expression, or efficiency at execution time? Here's a LINQ query which finds the declaration pretty quickly:

XmlDeclaration declaration = doc.ChildNodes()
                                .OfType<XmlDeclaration>()
                                .FirstOrDefault();

I strongly suspect that will be efficient enough. It's possible that you could just test whether the first child node was an XmlDeclaration... I don't think anything else can come before it.

If there's any possibility of using LINQ to XML instead, then it becomes even easier - you just use the XDocument.Declaration property.

Jon Skeet
@Jon, you're remembering right, the declaration can't have anything - including whitespace - before it, allowing for greater efficiency in both expression and execution.
Jon Hanna
A: 

To check it has one:

bool hasDec = doc.FirstChild.NodeType == XmlNodeType.XmlDeclaration;

To obtain it if it has one:

XmlDeclaration dec = doc.FirstChild as XmlDeclaration;

Remember that there is no content allowed prior to the XML declaration (barring a BOM, which isn't considered content, but an encoding artefact in the stream, so won't have a corresponding node).

Jon Hanna