私たちはWordで作成された絶対的に大量のヘルプ文書を持っています。これはもっと大量の、まれにHTM文書を生成するために使用されました。 C#とこのライブラリを使用して、アプリケーションの任意のポイントでこのファイルの1つのセクションだけを取得して表示します。セクションは次のように分割されます。
<!--logical section starts here -->
<div>
<h1><span style='mso-spacerun:yes'></span><a name="_Toc325456104">Section A</a></h1>
</div>
<div> Lots of unnecessary markup for simple formatting... </div>
.....
<!--logical section ends here -->
<div>
<h1><span style='mso-spacerun:yes'></span><a name="_Toc325456104">Section B</a></h1>
</div>
論理的には、 a
タグにセクション名を持つH1
があります。私は別のh1
に遭遇するまでdivを含む外側からすべてを選択し、そのdivを除外したい。
h1
<a>
タグ内にあります。 私の試み:
var startNode = helpDocument.DocumentNode.SelectSingleNode("//h1/a[contains(., '"+sectionName+"')]");
//go up one level from the a node to the h1 element
startNode=startNode.ParentNode;
//get the start index as the index of the div containing the h1 element
int startNodeIndex = startNode.ParentNode.ChildNodes.IndexOf(startNode);
//here I am not sure how to get the endNode location.
var endNode =?;
int endNodeIndex = endNode.ParentNode.ChildNodes.IndexOf(endNode);
//select everything from the start index to the end index
var nodes = startNode.ParentNode.ChildNodes.Where((n, index) => index >= startNodeIndex && index <= endNodeIndex).Select(n => n);
Sine私はこれに関する文書を見つけることができませんでした、私はどのように私のスタートノードから次のh1要素に得ることができないのか分かりません。任意の提案をいただければ幸いです。
H1タグはセクションヘッダーにしか表示されないものと仮定していますが、これでやると思います。そうでない場合は、子孫のWhereを追加して、見つかったH1ノード上の他のフィルタをチェックできます。これには、セクション名を持つ次のdivになるまで、divのすべての兄弟が含まれます。
private List<HtmlNode> GetSection(HtmlDocument helpDocument, string SectionName)
{
HtmlNode startNode = helpDocument.DocumentNode.Descendants("div").Where(d => d.InnerText.Equals(SectionName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
if (startNode == null)
return null; // section not found
List<HtmlNode> section = new List<HtmlNode>();
HtmlNode sibling = startNode.NextSibling;
while (sibling != null && sibling.Descendants("h1").Count() <= 0)
{
section.Add(sibling);
sibling = sibling.NextSibling;
}
return section;
}
ですから、あなたが本当に望んでいるのはh1-Tagの周りのdivですか?はいの場合、これはうまくいくはずです。
helpDocument.DocumentNode.SelectSingleNode("//h1/a[contains(@name, '"+sectionName+"')]/ancestor::div");
また、あなたのHTMLに応じてSelectNodes
動作します。このような:
helpDocument.DocumentNode.SelectNodes("//h1/a[starts-with(@name,'_Toc')]/ancestor::div");
ああ、これをテストしている間、私のために働いていないものがcontainsメソッドのドットであることに気がつきました。