2014-02-17 15 views
1
<html> 
<font color=#FF0000>Gaurang</font> 
<font color=#00FF00>Bhavesh</font> 
<font color=#FF0000>Bhupesh</font> 
<font color=#FF0000>AAditya</font> 
</html> 

我想解析上述字符串爲xml在C#中。 當我嘗試它給出錯誤,如'#'是一個意外的標記。預期令牌是。「「」或‘’'我想解析下面的字符串到XML使用C#

+2

你目前使用什麼解析? –

+1

我認爲這裏缺少的鏈接是你不能將它解析爲XML,因爲它不是有效的XML。 @ L.B的回答是正確的解決方案。 –

+0

考慮通過HtmlAgilityPack的CsQuery,因爲它更簡單,更快,更Moden。 'CQ.create(fileName)[「font」] .ToDictionary(e => e.InnerText「,e => e.Cq()。Attr(」color「))' –

回答

3

這似乎是一個HTML而不是XML,所以使用HtmlAgilityPack

var doc = new HtmlAgilityPack.HtmlDocument(); 
doc.Load(filename); 
var colors = doc.DocumentNode.Descendants("font") 
      .ToDictionary(e => e.InnerText, e => e.Attributes["color"].Value); 


foreach(var color in colors) 
{ 
    Console.WriteLine("{0}:{1}", color.Key, color.Value); 
} 
+0

嗨LB謝謝你的回答。但我想知道是否有可能這樣做,而不使用HtmlAgilityPack?我想避免使用第三方DLL。 – Gaurang

+1

@ user3180333只有部分工作的解決方案:http://stackoverflow.com/questions/1732348/regex-比賽開標籤 - 除了-XHTML-自足標籤 –

0

您發佈的樣本數據是不是有效的XML。有差異HTML和XML,其中之一是,大多數Web瀏覽器不要求各地值引號,但大多數XML解析器這樣做的,以下是有效的XML:

<font color="#FF0000">Gaurang</font> 

但這不是...

<font color=#FF0000>Gaurang</font>