2011-05-24 18 views
1

是否有一種簡單的方法可以從xml文件中只讀取XmlDeclaration而忽略其餘所有內容?具體而言,我想獲得聲明的編碼。我現在最好的事情:從xml文件中只讀XmlDeclaration

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

您目前的解決方案有什麼問題?它看起來確實以你想要的方式直截了當。 – svick 2011-05-24 19:41:13

+0

@svick:我想知道這個任務是否有一些內置的功能。 – 2011-05-25 07:25:17

回答

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()函數告訴讀者停止閱讀。這樣,只要你點擊聲明,你就可以得到編碼,然後離開它。