如何获取元素头或h1
本文关键字:元素 h1 获取 何获取 | 更新日期: 2023-09-27 18:25:30
我想得到标记<div>
中的head的值。但我还是拿不到。
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,我想得到的值是/Thefox/
<?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的字面意思是:
具有等于
ch1
的属性id
的任何a
元素
这是工作演示。