LoginSignup
0
1

More than 1 year has passed since last update.

C#でXMLを少し触ってみる

Last updated at Posted at 2022-08-05

目的

XPathDocumentとXmlDocumentで読み込んだXMLファイルに対して要素をさわってみる
メインはUsing XPathNavigator in C#のコードを参照(というか)
※.NET API は個数が多いので、使用箇所毎に記述してある

使用したデータ

Using XPathNavigator in C#のソースに含まれるxmlファイル(を正常に読めるように少し修正)

<?xml version="1.0" encoding="utf-8"?>
<books>
	<book category="Fiction" >
		<author>Jack Kerouac</author>
		<title>On the Road</title>
		<price>11.99</price>
	</book>
	<book category="IT" >
		<author>Stephen Walther</author>
		<title>ASP.NET Unleashed</title>
		<price>34.99</price>
	</book>
	<book category="Music" >
		<author>Michael Miller</author>
		<title>Idiots Guide to Music Theory</title>
		<price>17.99</price>
	</book>
	<book category="IT" >
		<author>Wrox</author>
		<title>Learning SQL</title>
		<price>15.99</price>
	</book>
	<book category="Non Fiction" >
		<author>Herman Hess</author>
		<title>Sidartha</title>
		<price>9.99</price>
	</book>
	<book category="Fiction" >
		<author>Jules Verne</author>
		<title>Journey to the Center of the Earth</title>
		<price>29.99</price>
	</book>
</books>

CSのサンプルコード

using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Collections;
using System.Diagnostics;


private void button6_Click(object sender, EventArgs e)
{
    //[Using XPathNavigator in C#]
    //(https://www.codeproject.com/articles/52079/using-xpathnavigator-in-c)
    XPathNavigator navigator = new XPathDocument(@"C:\data\books.xml").CreateNavigator();

    //[XPathNavigator.Evaluate メソッド]
    //(https://docs.microsoft.com/ja-jp/dotnet/api/system.xml.xpath.xpathnavigator.evaluate?view=net-6.0)
    
    Debug.Print("");
    foreach (XPathNavigator nav in (XPathNodeIterator)navigator.Evaluate("//book/*"))
    {
        Debug.Print("{0}={1}", nav.Name, nav.Value);
    }

    Debug.Print("");
    foreach (XPathNavigator nav in (XPathNodeIterator)navigator.Evaluate("//title"))
    {
        Debug.Print("{0}={1}", nav.Name, nav.Value);
    }

    //[XPathNavigator.Select メソッド]
    //(https://docs.microsoft.com/ja-jp/dotnet/api/system.xml.xpath.xpathnavigator.select?view=net-6.0)
    
    Debug.Print("");
    foreach (XPathNavigator nav in (XPathNodeIterator)navigator.Select("//book/title"))
    {
        Debug.Print("{0}={1}", nav.Name, nav.Value);
    }

    Debug.Print("");
    XPathNodeIterator nav0 = navigator.Select("//book/title");
    if (nav0.Count > 0)
    {
        while (nav0.MoveNext())
        {
            Debug.Print(nav0.Current?.Value);
        }
    }

    Debug.Print("");
    string query = "//book[@category=\'IT\']";
    foreach (XPathNavigator nav in (XPathNodeIterator)navigator.Select(query))
    {
        Debug.Print("{0}={1}", nav.Name, nav.Value);
    }

    Debug.Print("");
    XPathNodeIterator nav1 = navigator.Select(query);
    if (nav1.Count > 0)
    {
        while (nav1.MoveNext())
        {
            Debug.Print(nav1.Current?.Value);
        }
    }

    //[XmlNode.SelectNodes メソッド]
    //(https://docs.microsoft.com/ja-jp/dotnet/api/system.xml.xmlnode.selectnodes?view=net-6.0)
    //[XmlNode.SelectSingleNode メソッド]
    //(https://docs.microsoft.com/ja-jp/dotnet/api/system.xml.xmlnode.selectsinglenode?view=net-6.0)
    //[XmlNodeList クラス]
    //(https://docs.microsoft.com/ja-jp/dotnet/api/system.xml.xmlnodelist?view=net-6.0)
    //[C# XPathNavigator GetAttribute(string localName, string namespaceURI)]
    //(https://www.demo2s.com/csharp/csharp-xpathnavigator-getattribute-string-localname-string-namespaceuri.html)
    //(要素 - C#のXmlNodeから属性値を読み込む方法は?)
    //[https://code-examples.net/ja/q/186a41]

    Debug.Print("");
    Debug.Print("category");
    XPathNodeIterator nav2 = (XPathNodeIterator)navigator.Select("//book");
    Debug.Print(nav2.Count.ToString());

    foreach (XPathNavigator nav in (XPathNodeIterator)navigator.Select("//book"))
    {
        Debug.Print(nav.GetAttribute("category", String.Empty));
        Debug.Print(nav.SelectSingleNode("author")?.Value);
        Debug.Print(nav.SelectSingleNode("title")?.Value);
        Debug.Print(nav.SelectSingleNode("price")?.Value);
        Debug.Print("{0}={1}", nav.Name, nav.Value);
    }

    //[XmlNode.Attributes プロパティ]
    //(https://docs.microsoft.com/ja-jp/dotnet/api/system.xml.xmlnode.attributes?view=net-6.0)
    //[XML データを読み込む基本的な方法]
    //(https://csharp.keicode.com/topics/xml-selectnodes.php)
    Debug.Print("");
    Debug.Print("category");
    XmlDocument xdoc = new XmlDocument();
    xdoc.Load(@"C:\data\books.xml");
    //XmlNodeList xnodeList = xdoc.SelectNodes("books/book");
    Debug.Print(xdoc.SelectNodes("books/book")?.Count.ToString());
    foreach (XmlNode node in xdoc.SelectNodes("books/book"))
    {
        Debug.Print(node.Attributes["category"].Value);
        Debug.Print(node.SelectSingleNode("author")?.InnerText);
        Debug.Print(node.SelectSingleNode("title")?.InnerText);
        Debug.Print(node.SelectSingleNode("price")?.InnerText);
    }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1