【问题标题】:No html element when reading html string in XDocument在 XDocument 中读取 html 字符串时没有 html 元素
【发布时间】:2017-07-19 14:27:02
【问题描述】:

我阅读 HTML 的目的是从中提取<body> 的内容。

以下标记由DevExpress RichEditControl生成

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>
        </title>
        <style type="text/css">
            .cs95E872D0{text-align:left;text-indent:0pt;margin:0pt 0pt 0pt 0pt}
            .csCF6BBF71{color:#000000;background-color:transparent;font-family:Times New Roman;font-size:12pt;font-weight:normal;font-style:normal;}
        </style>
    </head>
    <body>
        <p class="cs95E872D0"><span class="csCF6BBF71">Content goes here</span></p></body>
</html>

按照this answer中关于如何阅读文档的示例,我编写了以下函数:

private string ParseHtml(string html)
{
    XDocument doc = XDocument.Parse(html);
    return doc.Elements("html").Single().Element("body").Value;
}

似乎理论上应该可行,但在实践中,LINQ 查询没有返回 .Elements("html") 的结果

我在这里是不是太离谱了?如何阅读 html 文档并提取我需要的内容?

【问题讨论】:

    标签: c# html linq linq-to-xml


    【解决方案1】:

    可能是因为需要添加命名空间:

     private string ParseHtml(string html)
     {
        XNamespace xmlns= "http://www.w3.org/1999/xhtml";
    
        XDocument doc = XDocument.Parse(html);
        return doc.Element(xmlns+"html").Element(xmlns+"body").Value;
     }
    

    或者:

    return doc.Descendants(xmlns+"body").Single().Value;
    

    还有一个解析 html 的好方法是使用 HTML Agility Pack

    【讨论】:

    • 只是添加 XNamespace 有一个 GetName 方法,XName 也有一个 get 方法。而不是硬编码命名空间 doc.Root.GetDefaultNamespace();将为您提供“w3.org/1999/xhtml”,如果您在元素中没有命名空间,它将起作用。
    猜你喜欢
    • 2017-12-09
    • 1970-01-01
    • 2014-09-20
    • 2021-07-08
    • 1970-01-01
    • 2019-01-28
    • 2011-07-21
    • 2016-05-28
    • 1970-01-01
    相关资源
    最近更新 更多