从xml文件中只读XmlDeclaration

时间:2011-05-24 17:15:35

标签: .net xml

是否有一种简单的方法可以从xml文件中只读取XmlDeclaration而忽略其余部分?具体来说,我想获得声明的编码。我现在最好的事情是:

using (var reader = new XmlTextReader(path))
    if (reader.Read() && reader.NodeType == XmlNodeType.XmlDeclaration)
    {
        Console.WriteLine(reader.GetAttribute("encoding"));
    }

1 个答案:

答案 0 :(得分:1)

此页面可以帮助您:http://support.microsoft.com/kb/308061。 向下滚动到“读者的编码属性”页面,略低于页面的一半。他们有:

        // 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);

所以我猜,读者包含一个内置的编码功能,但你的方式非常简单,做得好,不确定是否真的有一种“更容易”的方法来做到这一点。您还可以通过使用reader.close()函数告诉读者停止阅读。这样,只要你点击声明,你就会得到编码而你就离开了。