[案例] 我已經用元數據瞭解了一大堆'xml文件',其中包含大量文檔。至少,這是我所要求的。我收到其中「XML文件」沒有根元素,它們的結構是這樣的(我留下了一堆元素):在XmlTextReader對象中讀取'假'xml文檔(xml片段)
<folder name = "abc"></folder>
<folder name = "abc/def">
<document name = "ghi1">
</document>
<document name = "ghi2">
</document>
</folder>
[問題] 當我試圖讀取該文件它失敗的XmlTextReader對象告訴我沒有根元素。
[當前的解決方法] 當然,我可以讀取該文件作爲流附加< xmlroot>和</xmlroot>和流寫入到一個新的文件,並讀出一個在XmlTextReader的中。這正是我現在正在做的,但我更喜歡不「篡改」原始數據。
[請求的解決方案] 據我所知,我應該爲此使用XmlTextReader,並帶有DocumentFragment選項。然而,這給編譯時錯誤:
An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
Additional information: XmlNodeType DocumentFragment is not supported for partial content parsing. Line 1, position 1.
[故障代碼]
using System.Diagnostics;
using System.Xml;
namespace XmlExample
{
class Program
{
static void Main(string[] args)
{
string file = @"C:\test.txt";
XmlTextReader tr = new XmlTextReader(file, XmlNodeType.DocumentFragment, null);
while(tr.Read())
Debug.WriteLine("NodeType: {0} NodeName: {1}", tr.NodeType, tr.Name);
}
}
}
您正在使用過時的方法...自.NET 4以來XmlDataDocuments已過時 – 2013-02-23 08:43:06
現在使用XmlTextReader類更改了問題。 – 2013-02-23 10:05:42
實際上自.NET 2.0以來,XmlTextReader已被棄用。改爲使用XmlReader.Create。 – 2013-02-23 10:50:14