我怎样才能得到元素 head 或 h1

how can i get the element head or h1

我想获取标签 <div> 内的头部值。但我还是无法得到它。

var source = inputXDoc.Descendants(GetNamespace(ref namespace2, "").GetName("body"));
if (source.Descendants(GetNamespace(ref namespace2, "").GetName("div")).Any())
{
    var introduced5 = inputXDoc.Descendants(GetNamespace(ref namespace2, "").GetName("body"));
    if (introduced5.Descendants(GetNamespace(ref namespace2, "").GetName("div")).First().Attributes("id").Any())
    {
        var introduced6 = inputXDoc.Descendants(GetNamespace(ref namespace2, "").GetName("body"));
        //_chapterName = introduced6.Descendants(GetNamespace(ref namespace2, "").GetName("div")).First().Attributes("id").First().Value;
        _chapterName = introduced6.Descendants(GetNamespace(ref namespace2, "").GetName("div")).First().Element("h")?.Value;
    }
}

下面是html,我要获取的值是/The fox/

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xml:lang="" xmlns="">
    <head>
        <title>De title</title>
        <link rel="stylesheet" type="text/css" href="Digital.css"/>
    </head>
    <body>
        <h1>
            <a id="p7"/>
            <a id="ch1" href="005_inhoud.html#ch1">/The fox/</a>
        </h1>
        <p class="indent">the quick brown fox jump over the lazy dog</p>
    </body>
</html>

您可以简单地使用 XPath 扩展来提取元素:

using System.Xml.XPath;

string title = inputXDoc.XPathSelectElement("//a[@id='ch1']").Value;

这个 XPath 的字面意思是:

any a element having an attribute id equal to ch1

这里是the working demo