What is the more efficient way to check an XmlDocument for an XmlDeclaration node?
The XmlDocument represents an XML document. It can be use to load, modify, validate, an navigate XML documents. The XmlDocument class is an in-memory representation of an XML document. It implements the W3C XML Document Object Model (DOM).
An XML declaration is a processing instruction that identifies a document as XML. DITA documents must begin with an XML declaration.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With