2017-09-11 11 views
2

私はhtmlを解析するためにforeachループを持っており、私はxpathを使っています。どのような私は必要なのforeachループ用の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; 
      } 

     } 

私は何をしようとしているセクションをループがあると、特定のセクションの下に、各サブセクションを見つけるいくつかの処理を行い、その特定のセクションの下のサブセクションを見つけるために、次のセクションに移動し、次のです。

+3

'私は、foreachループを持っている... VS2015 + XSLTで...

foreach (var subSection in (section.SelectNodes("following-sibling::p") ?? Enumerable.Empty<HtmlNode>()) .TakeWhile(n => n.Attributes["class"].Value != "section")) 

...同じものを使用していない場合htmlをパースし、xpathを使用しています.'そのコードを表示してください。 – mjwills

+1

なぜxpathでこれをやろうとしていますか? 'XSLT'、' XPathNavigator'、または 'LINQ to XML'を使用していますか? –

+0

@mjwillsがforeachループコードを追加する投稿を更新しました –

答えて

0

変数を参照できないため、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 
*/ 

...あなたは

<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> 
+0

ありがとうございます。私はそれを次のxpathで動作させました - .// p [@ class = 'section-e'] ["+ count +"]/following-sibling :: p [@ class = 'subsection-e' -sibling :: p [@ class = 'section-e'])= "+ count +"] countは渡されたセクションタグの数です。しかし、私はポイントと簡潔にあなたのlinqバージョンをより好きだった。 –