我有一个 foreach 循环来解析 html,我正在为它使用 xpath。我需要的是关注
<p class="section">sectiontext1</p>
<p class="subsection">subtext1</p> ----need this in first loop
<p class="subsection">subtext2</p> ---need this in first loop
<p class="section">sectiontext2</p>
<p class="subsection">subtext11</p> ---need this in second loop
<p class="subsection">subtext22</p> ---- need this in second loop
<p class="section">sectiontext3</p>
foreach (HtmlNode sectionNode in htmldocObject.DocumentNode.SelectNodes("//p[@class='section']"))
{
count=count+2;
string text1 = sectionNode.InnerText;
foreach (HtmlNode subSectionNode in htmldocObject.DocumentNode.SelectNodes("//p[@class='subsection'][following-sibling::p[@class='section'][1] and preceding-sibling::p[@class='section'][2]]"))
{
string text = subSectionNode.InnerText;
}
}
我想做的是遍历各个部分并找到特定部分下的每个小节,进行一些处理,然后移至下一个部分以找到该特定部分下的小节。
最佳答案
我无法让 XPath 正常工作,因为您无法引用变量...但您可以使用 LINQ
修复您的查询。
foreach (var section in html.DocumentNode.SelectNodes("//p[@class='section']"))
{
Console.WriteLine(section.InnerText);
foreach (var subSection in section?.SelectNodes("following-sibling::p")
?.TakeWhile(n => n?.Attributes["class"]?.Value != "section")
?? Enumerable.Empty<HtmlNode>())
Console.WriteLine("\t" + subSection.InnerText);
}
/*
sectiontext1
subtext1-1
subtext1-2
sectiontext2
subtext2-11
subtext2-22
sectiontext3
*/
...如果您没有使用 VS2015+ ...
foreach (var subSection in (section.SelectNodes("following-sibling::p") ?? Enumerable.Empty<HtmlNode>())
.TakeWhile(n => n.Attributes["class"].Value != "section"))
... XSLT 中的相同内容...
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="yes"/>
<xsl:template match="/">
<xsl:for-each select="//p[@class='section']">
<xsl:variable name="start" select="." />
<xsl:value-of select="text()"/><xsl:text> </xsl:text>
<xsl:for-each select="following-sibling::p[@class='subsection'][preceding-sibling::p[@class='section'][1]=$start]">
<xsl:text>	</xsl:text><xsl:value-of select="text()"/><xsl:text> </xsl:text>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
关于c# - foreach循环的xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46164245/