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
2010-08-19 09:12:32
@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
2010-08-19 22:41:19
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
2010-08-19 22:38:40