Xamarin: XMLのパース

概要

XamarinでSystem.Xml.XmlDocumentを使用してXMLのパースを行う。

docs.microsoft.com

サンプルXML

テスト用に以下のXMLファイルをリソースIDXamarinTest.SampleXmlFile.xmlでプロジェクト内に追加する。

参照: www.wired-cat.com

<?xml version="1.0" encoding="utf-8"?>  
<books xmlns = "http://www.contoso.com/books" >
  <book genre="novel" ISBN="1-861001-57-8" publicationdate="1823-01-28">  
    <title>Pride And Prejudice</title>  
    <price>24.95</price>  
  </book>  
  <book genre = "novel" ISBN="1-861002-30-1" publicationdate="1985-01-01">  
    <title>The Handmaid's Tale</title>  
    <price>29.95</price>  
  </book>  
  <book genre = "novel" ISBN="1-861001-45-3" publicationdate="1811-01-01">  
    <title>Sense and Sensibility</title>  
    <price>19.95</price>  
  </book>  
</books>  

サンプルコード

void TestReadXmlDocument()
{
    string xmlFileData = GetResourceFileData("XamarinTest.SampleXmlFile.xml");
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xmlFileData);

    XmlNodeList bookList = doc.GetElementsByTagName("book");
    for (int i = 0; i < bookList.Count; i++)
    {
        XmlNode book = bookList.Item(i);
        Console.WriteLine("--- book[" + i + "] ---");
        Console.WriteLine("title=" + (book["title"] != null ? book["title"].InnerText : ""));
        Console.WriteLine("price=" + (book["price"] != null ? book["price"].InnerText : ""));
        Console.WriteLine("test=" + (book["test"] != null ? book["test"].InnerText : ""));
    }
}

private String GetResourceFileData(String fileName)
{
    var assembly = typeof(MainPage).GetTypeInfo().Assembly;
    Stream stream = assembly.GetManifestResourceStream(fileName);  // A)
    using (var reader = new System.IO.StreamReader(stream))
    {
        return reader.ReadToEnd();
    }
}

実行結果

--- book[0] ---
title=Pride And Prejudice
price=24.95
test=
--- book[1] ---
title=The Handmaid's Tale
price=29.95
test=
--- book[2] ---
title=Sense and Sensibility
price=19.95
test=