开发者

Read only XmlDeclaration from the xml file

Is there an easy way to read only XmlDeclaration from the xml file disregarding all the rest of it? Specifically I want to get declared encoding. The best thing I have now:

using (var reader = new XmlTextReader(path))
    if (reader.Read() && reader.NodeType == XmlNodeType.XmlDeclaration)
    {
        Console.WriteLine(reader.Get开发者_StackOverflowAttribute("encoding"));
    }


this page may help you: http://support.microsoft.com/kb/308061. Scroll down to "The Encoding Property of the Readers" page, a little lower than halfway down the page. They have:

        // Reading the encoding using the reader classes.
        XmlTextReader rdr = new XmlTextReader("Q308061.xml");
        rdr.Read();
        Console.WriteLine("Encoding from the reader: {0} \n\n", rdr.Encoding.EncodingName);

So I'm guessing, the reader includes a built in function for encoding, but the way you have is quite.. simplified and well done, not sure if there actually is an "easier" way to to do it. You could also tell the reader to stop reading by using the reader.close() function. That way, as soon as you hit the declaration, you get the encoding and you leave it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜