2012-07-31 27 views
0

我使用HtmlAgilityPack從字符串肌酸一個HTMLDocument的,喜歡XML:使用LINQ與Htmlagilitypack

HtmlDocument updoc = new HtmlDocument(); 
    updoc.load(stringContents); 

現在我想插入HtmlNodes作爲的XElement的孩子。我想:

XDocument xdoc = XDocument.load(path); 
    XElement body = xdoc.Descendants(ns + "body").Single(); 
    body.Add(updoc.GetElementbyId("h")); 
    body.Add(updoc.GetElementbyId("m")); 
    body.Add(updoc.GetElementbyId("f")); 

,但結果只會對象名稱(HtmlNodeAgilityPack,..),沒有工作。基本上我正在嘗試將HtmlAgilityPack和linq結合使用到xml。這可能嗎 ?

回答

0

我只是谷歌搜索周圍的東西解析它,所以這可能不適合你。但是您需要使用由GetElementbyId()返回的HtmlNode的屬性來創建您的元素。

因此,像這樣:

HtmlNode node = updoc.GetElementbyId("h"); 
XElement e; 
body.Add(e = new XElement(node.Name, XElement.Parse(node.InnerHtml))); 

如果節點HtmlAttribute(S),將它們添加喜歡:

foreach(HtmlAttribute att in node.Attributes) 
{ 
    e.Add(new XAttribute(att.Name, att.Value)); 
} 
0

爲什麼不直接使用StringBuilder來生成XML並以XDocument.Parse(string)

Example : 

StringBuilder xmlBuilder = new StringBuilder(); 
//Build xml with the builder 
XDocument xDoc = XDocument.Parse(xmlBuilder.ToString());