c# - foreach循环的xpath

标签 c# xpath foreach

我有一个 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>&#10;</xsl:text>
        <xsl:for-each select="following-sibling::p[@class='subsection'][preceding-sibling::p[@class='section'][1]=$start]">
            <xsl:text>&#9;</xsl:text><xsl:value-of select="text()"/><xsl:text>&#10;</xsl:text>
        </xsl:for-each>
      </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

关于c# - foreach循环的xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46164245/

相关文章:

c# - 有没有办法在 WPF 窗口内托管 DirectX12 应用程序?

c# - 实现简单的 Pong AI 时,会创建两个 Racket 并闪烁

XPath - 基于多个子选择选择父节点

php - 如何将 CSS 添加到 CodeIgniter View 中的 foreach 结果?

php - 在PHP中,如何在foreach循环中播放数据库中的音频?

c# - azure function c# http trigger blob output

c# - Windows 10 BackgroundMediaPlayer SystemTransportControls 暂停按钮不工作

xml - 使用 XPath 在命名空间中选择元素

html - GoLang - 带有 HTML 的 XmlPath 选择器

for循环期间的Javascript关联数组修改