【问题标题】:Linq XML How to ignore html code?Linq XML 如何忽略 html 代码?
【发布时间】:2011-10-15 18:28:17
【问题描述】:

我正在使用 Xelement - Linq to XML 来解析一些 RSS 提要。

Rss 示例:

    <item>
      <title>Waterfront Ice Skating</title>
      <link>http://www.eventfinder.co.nz/2011/sep/wellington/wellington-waterfront-ice-skating?utm_medium=rss</link>
      <description>&lt;p&gt;An ice skating rink in Wellington for a limited time only! 

Enjoy the magic of the New Zealand winter at an outdoor skating experience with all the fun and atmosphere of New York&amp;#039;s Rockefeller Centre or Central Park, ...&lt;/p&gt;&lt;p&gt;Wellington | Friday, 30 September 2011 - Sunday, 30 October 2011&lt;/p&gt;</description>
      <content:encoded><![CDATA[Today, Wellington Waterfront<br/>Wellington]]></content:encoded>
      <guid isPermalink="false">108703</guid>
      <pubDate>2011-09-30T10:00:00Z</pubDate>
      <enclosure url="http://s1.eventfinder.co.nz/uploads/events/transformed/190501-108703-13.jpg" length="5000" type="image/jpeg"></enclosure>
    </item>

一切正常,但描述元素有很多我需要删除的 html 标记。

说明:

<description>&lt;p&gt;An ice skating rink in Wellington for a limited time only! 

    Enjoy the magic of the New Zealand winter at an outdoor skating experience with all the fun and atmosphere of New York&amp;#039;s Rockefeller Centre or Central Park, ...&lt;/p&gt;&lt;p&gt;Wellington | Friday, 30 September 2011 - Sunday, 30 October 2011&lt;/p&gt;</description>

有人可以帮忙吗?

【问题讨论】:

  • “忽略 html 代码”是什么意思。您要提取纯文本吗?
  • @AVD 是的,我只想提取文本,忽略标记。
  • 看看这个链接 - dotnetperls.com/remove-html-tags

标签: c# linq windows-phone-7


【解决方案1】:

如果是 RSSFeed,为什么不使用 System.ServiceModel.Syndication,SyncicationFeed 结合 XML 阅读器将处理您的 XmlEncoded 问题

            using (XmlReader reader = XmlReader.Create(@"C:\\Users\\justMe\\myXml.xml"))
            {
                SyndicationFeed myFeed = SyndicationFeed.Load(reader);
                ...
            }

然后按照@nemesv 的建议使用正则表达式删除 HTML-Tags,或使用类似的东西

    public static string StripHTML(this string htmlText)
    {
        var reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
        return HttpUtility.HtmlDecode(reg.Replace(htmlText, string.Empty));
    }

【讨论】:

    【解决方案2】:

    首先你应该用System.Net.HttpUtility.HtmlDecode对描述的内容进行HtmlDecode。这会将编码的 &amp;lt ;p&amp;gt ; 替换为

    然后您可以使用正则表达式删除 HTML 标签:Using C# regular expressions to remove HTML tags 或其他一些 HTML 解析库。

    【讨论】:

    • 不,它是 XmlEncoded,而不是 HtmlEncoded。只需获取 XElement.Value 即可,HtmlDecode 可能会出错。
    猜你喜欢
    • 2012-05-16
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    • 2021-05-21
    相关资源
    最近更新 更多