[英]Using linq to xml with Htmlagilitypack
我正在使用HtmlAgilityPack从字符串创建html文档,例如:
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。 这可能吗 ?
为什么不只使用StringBuilder生成xml并使用XDocument.Parse(string)对其进行解析
Example :
StringBuilder xmlBuilder = new StringBuilder();
//Build xml with the builder
XDocument xDoc = XDocument.Parse(xmlBuilder.ToString());
我只是在四处寻找东西,因此这可能对您不起作用。 但是您需要使用GetElementbyId()
返回的HtmlNode的属性来创建元素。
所以像这样:
HtmlNode node = updoc.GetElementbyId("h");
XElement e;
body.Add(e = new XElement(node.Name, XElement.Parse(node.InnerHtml)));
如果节点具有HtmlAttribute ,则将它们添加为:
foreach(HtmlAttribute att in node.Attributes)
{
e.Add(new XAttribute(att.Name, att.Value));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.