XPathを指定し、特定ノードの値を取得するサンプル

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using System.Xml;
  11. using System.IO;
  12. namespace WindowsFormsApplication1
  13. {
  14.     public partial class Form1 : Form
  15.     {
  16.         public Form1()
  17.         {
  18.             InitializeComponent();
  19.         }
  20.         /**
  21.          * ファイルを開く
  22.          */
  23.         private void button1_Click(object sender, EventArgs e)
  24.         {
  25.             OpenFileDialog ofd = new OpenFileDialog();
  26.             // XMLのみ指定
  27.             ofd.Filter = "XMLファイル(*.xml)|*.xml";
  28.             // ダイアログ表示
  29.             DialogResult dialogResult = ofd.ShowDialog();
  30.             // 開くが押された場合
  31.             if (dialogResult == DialogResult.OK)
  32.             {
  33.                 textBox1.Text = ofd.FileName;
  34.                 String file = textBox1.Text;
  35.                 // XMLを読み込み、内容をテキストボックスに出力
  36.                 StreamReader sr = new StreamReader(file);
  37.                 richTextBox1.Text = sr.ReadToEnd();
  38.             }
  39.         }
  40.         /**
  41.          * ノードの値を取得
  42.          */
  43.         private void button2_Click(object sender, EventArgs e)
  44.         {
  45.             // 取得結果をクリア
  46.             textBox3.Text = "";
  47.             if (!"".Equals(textBox1.Text) && !"".Equals(textBox2.Text))
  48.             {
  49.                 XmlDocument xml = new XmlDocument();
  50.                 // XML読み込み
  51.                 xml.Load(textBox1.Text);
  52.                 // 指定されたXPathのノードを取得
  53.                 XmlNodeList nodeList = xml.SelectNodes(textBox2.Text);
  54.                 foreach (XmlNode node in nodeList)
  55.                 {
  56.                     // 取得結果をセット
  57.                     textBox3.Text = node.InnerText;
  58.                 }
  59.             }
  60.         }
  61.     }
  62. }

image

実行ファイルダウンロード

戻る