該当した最初のノード、またはn番目のノードを選択するXPathの記述方法 - C#

該当したノードのうち最初のノードを選択するXPathの記述方法を紹介します。

書式

XPathで該当したノードのうち最初のノードを選択する場合は次の書式を用います。
(パス)[1]

n番目のノードを選択する場合のXPathはは次の書式を用います。
(パス)[n]

/root/node/data の最初のノードを選択する場合のXPathは下記です。
 (/root/node/data)[1]

/root/node/dataにマッチする2番目のノードを選択します。
 (/root/node/data)[2]

コード例

private void button3_Click(object sender, EventArgs e)
{
  XmlDocument xmlDocument = new XmlDocument();
  xmlDocument.Load(textBox1.Text);

  XmlNodeList nodeList = xmlDocument.SelectNodes("(/root/node/data)[1]");
      
  for (int i=0; i < nodeList.Count; i++){
    textBox2.Text += "NodeType: " + nodeList[i].NodeType + "\r\n";
    textBox2.Text += "Name: " + nodeList[i].Name + "\r\n";
    textBox2.Text += "LocalName: " + nodeList[i].LocalName + "\r\n";
    textBox2.Text += "Value: " + nodeList[i].Value + "\r\n";
    textBox2.Text += "InnerText: " + nodeList[i].InnerText + "\r\n";
    textBox2.Text += "\r\n";
    if (nodeList[i].HasChildNodes == true){
      for (int j=0; j < nodeList[i].ChildNodes.Count; j++) {
        textBox2.Text += "NodeType: " + nodeList[i].ChildNodes[j].NodeType + "\r\n";
        textBox2.Text += "Name: " + nodeList[i].ChildNodes[j].Name + "\r\n";
        textBox2.Text += "LocalName: " + nodeList[i].ChildNodes[j].LocalName + "\r\n";
        textBox2.Text += "Value: " + nodeList[i].ChildNodes[j].Value + "\r\n";
        textBox2.Text += "InnerText: " + nodeList[i].ChildNodes[j].InnerText + "\r\n";
      }
    }
    textBox2.Text += "\r\n";
  }
}

入力データ (XMLファイル)

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
  <node>
    <data type="text">データ1です</data> 
  </node>
  <node> 
    <data type="text">データ2です</data> 
  </node>
  <node>
    <data type="text">データ3です</data> 
  </node>
</root>

実行結果

NodeType: Element
Name: data
LocalName: data
Value: 
InnerText: データ1です

NodeType: Text
Name: #text
LocalName: #text
Value: データ1です
InnerText: データ1です

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2011-01-07
iPentec all rights reserverd.