XML解析

C#XMLを解析する。



■解析するXML(test.xml)■










■解析コード■

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Test
{
class Program
{
static void Main(string[] args)
{
// Xml解析用
System.Xml.XmlTextReader xmlTextReader = new XmlTextReader("../../test.xml");

while (xmlTextReader.Read())
{
if (xmlTextReader.NodeType == XmlNodeType.Element)
{
if (xmlTextReader.Name == "Element0")
{
Console.WriteLine("■Element0■");
            // アトリビュート値を名前で取得
string strAttribute0 = xmlTextReader.GetAttribute("attribute0");
string strAttribute1 = xmlTextReader.GetAttribute("attribute1");
string strAttribute2 = xmlTextReader.GetAttribute("attribute2");
string strAttribute3 = xmlTextReader.GetAttribute("attribute3");
string strAttribute4 = xmlTextReader.GetAttribute("attribute4");
Console.WriteLine("strAttribute0 = " + strAttribute0);
Console.WriteLine("strAttribute1 = " + strAttribute1);
Console.WriteLine("strAttribute2 = " + strAttribute2);
Console.WriteLine("strAttribute3 = " + strAttribute3);
Console.WriteLine("strAttribute4 = " + strAttribute4);
}
else if (xmlTextReader.Name == "Element1")
{
string[] strAttributes = new string[5];
Console.WriteLine("■Element1■");
for (int iAtt = 0; iAtt < 5; iAtt++)
{
              // アトリビュート値をインデックスで取得
strAttributes[iAtt] = xmlTextReader.GetAttribute(iAtt);
Console.WriteLine("strAttribute" + iAtt + "= " + strAttributes[iAtt]);
}
}
else if (xmlTextReader.Name == "Element2")
{
Console.WriteLine("■Element2■");
string hello = xmlTextReader.GetAttribute(0);
Console.Write("hello = " + hello);
}
}
}
}
}
}

■結果■


■Element0■
strAttribute0 = あ
strAttribute1 = い
strAttribute2 = う
strAttribute3 = え
strAttribute4 = お
■Element1■
strAttribute0= か
strAttribute1= き
strAttribute2= く
strAttribute3= け
strAttribute4= こ
■Element2■
hello = こんにちわ
続行するには何かキーを押してください . . .←

.NetFrameworkにはXmlTextReaderとXmlReaderがあるが、今回はXmlTextReaderを使用しました。