該当した最後のノードを選択するXPathの記述方法 - C#

書式

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

 (/root/node/data)[last()]

コード例

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

  XmlNodeList nodeList = xmlDocument.SelectNodes("(/root/node/data)[last()]");
      
  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: データ3です

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


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