How to check XmlDeclaration in XmlDocument C #

What is a more efficient way to validate an XmlDocument for an XmlDeclaration node?

+5
source share
2 answers

What "efficiency" are you after? Expression efficiency or runtime efficiency? Here is a LINQ query that quickly finds an ad:

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

I strongly suspect that it will be quite effective. Perhaps you could just check to see if there was a first child node XmlDeclaration... I don't think anything else might appear in front of it.

If you can use LINQ to XML, then it becomes even easier - you just use the property XDocument.Declaration.

+6
source

To check if it has one:

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

, :

XmlDeclaration dec = doc.FirstChild as XmlDeclaration;

, XML ( , , , node).

+8

All Articles