C# 如何在XML中获取内部标记值?
如果我使用注释行代码(C# 如何在XML中获取内部标记值?,c#,asp.net,xml,xml-parsing,C#,Asp.net,Xml,Xml Parsing,如果我使用注释行代码(string content=item.Element(nsContent+“encoded”).Value;)而不是循环的内部,那么它将获取元素的值,但它包含所有链接、图像等,我只需要文本 为此,我尝试使用此过滤器(内部For循环),但其显示错误: 对象引用未设置为对象的实例 请向我推荐代码,以便我只能存储文本并删除所有其他链接、标记等。首先,我将使用StringBuilder开始: XDocument coordinates = XDocument.Load("http
string content=item.Element(nsContent+“encoded”).Value;
)而不是循环的内部,那么它将获取
元素的值,但它包含所有链接、图像等,我只需要文本
为此,我尝试使用此过滤器(内部For循环),但其显示错误:
对象引用未设置为对象的实例
请向我推荐代码,以便我只能存储文本并删除所有其他链接、标记等。首先,我将使用StringBuilder开始:
XDocument coordinates = XDocument.Load("http://feeds.feedburner.com/TechCrunch");
System.IO.StreamWriter StreamWriter1 = new System.IO.StreamWriter(DestFile);
XNamespace nsContent = "http://purl.org/rss/1.0/modules/content/";
string pchild = null;
foreach (var item in coordinates.Descendants("item"))
{
string link = item.Element("guid").Value;
//string content = item.Element(nsContent + "encoded").Value;
foreach (var child in item.Descendants(nsContent + "encoded"))
{
pchild = pchild + child.Element("p").Value;
}
StreamWriter1.WriteLine(link + Environment.NewLine + Environment.NewLine + pchild + Environment.NewLine);
}
StreamWriter1.Close();
然后,我怀疑有时“child”没有“p”元素,因此您可以在使用它之前进行检查:
StringBuilder sb = new StringBuilder();
这对您有用吗?item.Element(nsContent+“encoded”)的内容。Value
是html而不是xml。您应该相应地解析它,例如使用
请参见下面的示例
foreach (var child in item.Descendants(nsContent + "encoded"))
{
if (child.Element("p") != null)
{
sb.Append(child.Element("p").Value);
}
}
StreamWriter1.WriteLine(link + Environment.NewLine + Environment.NewLine + sb.ToString() + Environment.NewLine);
是的,不起作用,因为所有元素都在CDATA节点内。。。这需要更多的工作。抱歉,Join
是我自己的扩展方法。我更新了答案
string content = item.Element(nsContent + "encoded").Value;
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(new StringReader(content));
var text = String.Join(Environment.NewLine + Environment.NewLine,
doc.DocumentNode
.Descendants("p")
.Select(n => "\t" + System.Web.HttpUtility.HtmlDecode(n.InnerText))
);