Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for XmlDeclaration in XmlDocument C#

Tags:

c#

xml

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

like image 215
adamwtiko Avatar asked Aug 19 '10 09:08

adamwtiko


People also ask

What is the use of XmlDocument?

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).

What is the XML declaration?

An XML declaration is a processing instruction that identifies a document as XML. DITA documents must begin with an XML declaration.


2 Answers

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).

like image 99
Jon Hanna Avatar answered Nov 13 '22 05:11

Jon Hanna


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.

like image 45
Jon Skeet Avatar answered Nov 13 '22 04:11

Jon Skeet