c# - xpath for foreach loop -
i have foreach loop parse html , using xpath it. need following
<p class="section">sectiontext1</p> <p class="subsection">subtext1</p> ----need in first loop <p class="subsection">subtext2</p> ---need in first loop <p class="section">sectiontext2</p> <p class="subsection">subtext11</p> ---need in second loop <p class="subsection">subtext22</p> ---- need 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] , preceding-sibling::p[@class='section'][2]]")) { string text = subsectionnode.innertext; } }
what trying loop through sections , find each subsections under specific section, processing , move next section find subsections under particular section.
i couldn't xpath work correctly since can't reference variables... can fix query 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 */
... if aren't using vs2015+ ...
foreach (var subsection in (section.selectnodes("following-sibling::p") ?? enumerable.empty<htmlnode>()) .takewhile(n => n.attributes["class"].value != "section"))
... same thing in 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>
Comments
Post a Comment