2017-05-21 281 views
1

我有這樣的XML數據爲什麼我在嘗試加載xml文件時解析EntityName時發生錯誤?

<Categories> 
    <cat name="Appliances"></cat> 
    <cat name="Arts, Crafts & Sewing"></cat> 
    <cat name="Automotive"></cat> 
    <cat name="Baby"></cat> 
</Categories> 

,我用這個代碼將數據讀入組合框:

XmlDocument xDoc = new XmlDocument(); 
xDoc.Load("cat.xml"); 
XmlNodeList cats = xDoc.GetElementsByTagName("cat"); 
for (int i = 0; i < cats.Count; i++) 
{ 
    comboBox1.Items.Add(cats[i].Attributes["name"].InnerText); 
} 

,但在行xDoc.Load("cat.xml");我得到錯誤:

An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll An error occurred while parsing EntityName. Line 3, position 30.

這是什麼意思 ?

+1

參加【這裏這個問題]看看(http://stackoverflow.com/questions/23541910/an-error-之前嘗試此發生時,解析實體名稱行1位置844),並告訴我,如果它可以幫助你。 – Alisson

回答

1

你的XML包含一個符號,使之無效,解析

var xmlContent = File.ReadAllText("cat.xml"); 
XmlDocument xDoc = new XmlDocument(); 
xDoc.LoadXml(xmlContent.Replace("&", "&amp;")); 
+0

我試過'xDoc.LoadXml(SecurityElement.Escape(xmlContent));'但我現在得到錯誤在根級別的數據是無效的。第1行,第1位。 – Wel

+2

@你不能在這裏使用'SecurityElement.Escape'(這是@Alisson編輯錯誤,我將刪除它),因爲它甚至會替換'<' and '>',但你需要替換隻有&符號。使用'xmlContent.Replace(「&」,「&」)' – Marusyk

相關問題