简体   繁体   English

简单的XPath查询:无结果

[英]Simple XPath query: no results

I want to parse the HTML of a website in my C# program. 我想在我的C#程序中解析网站的HTML。

First, I use the SGMLReader DLL to convert the HTML to XML. 首先,我使用SGMLReader DLL将HTML转换为XML。 I use the following method for this: 为此,我使用以下方法:

XmlDocument FromHtml(TextReader reader)
{
    // setup SGMLReader
    Sgml.SgmlReader sgmlReader = new Sgml.SgmlReader();
    sgmlReader.DocType = "HTML";
    sgmlReader.WhitespaceHandling = WhitespaceHandling.None;
    sgmlReader.CaseFolding = Sgml.CaseFolding.ToLower;
    sgmlReader.InputStream = reader;

    // create document
    XmlDocument doc = new XmlDocument();
    doc.PreserveWhitespace = true;
    doc.XmlResolver = null;
    doc.Load(sgmlReader);
    return doc;
}

Next, I read a website and try to look for the header node: 接下来,我阅读了一个网站并尝试查找header节点:

var client = new WebClient();
var xmlDoc = FromHtml(new StringReader(client.DownloadString(@"http://www.switchonthecode.com")));
var result = xmlDoc.DocumentElement.SelectNodes("head");

However, this query gives an empty result (count == 0). 但是,此查询给出的结果为空(计数== 0)。 But when I inspect the results view of xmlDoc.DocumentElement, I see the following: 但是,当我检查xmlDoc.DocumentElement的结果视图时,会看到以下内容:

VS手表

Any idea's why there are no results? 知道为什么没有结果吗? Note that when I try another site, like http://www.google.com , it works. 请注意,当我尝试其他网站(例如http://www.google.com)时 ,它可以工作。

You need to select using the namespace explicitly, see this question . 您需要显式选择使用名称空间,请参见此问题

XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("ns", "http://www.w3.org/1999/xhtml");

doc.DocumentElement.SelectNodes("ns:head", manager);

You can use HTML Agility Pack instead. 您可以改用HTML Agility Pack It's an open source HTML parser 这是一个开放源代码的HTML解析器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM