23
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Unity C# XMLのパース

Last updated at Posted at 2014-08-06

.NET Framework の System.Xml を使う。

XMLサンプル

<talks>
    <talk person="2">
        <speak content="こんにちは" num="1" />
        <speak content="ありがとう" num="2" />
        <speak content="さようなら" num="3" />
    </talk>
    <talk person="1">
        <speak content="あーい" num="4" />
        <speak content="ふーい" num="5" />
        <speak content="ねむい" num="6" />
    </talk>
</talks>

スクリプト

上記のXMLをstring型で渡す。

using UnityEngine;

using System.Xml;
using System.IO;

public class SampleMain {

    public void XmlPerse ( string xmlString ) { // string型で渡ってきたとする

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(new StringReader(xmlString));

        XmlNode root = xmlDoc.FirstChild;

        XmlNodeList talkList = xmlDoc.GetElementsByTagName("talk");

        XmlNode talk0 = talkList[0];
        XmlNode talk1 = talkList[1];

        XmlNodeList speakList0 = talk0.ChildNodes;
        XmlNodeList speakList1 = talk1.ChildNodes;

        Debug.Log( root.Name ); // talks

        Debug.Log( talk0.Attributes["person"].Value ); // 2
        Debug.Log( talk1.Attributes["person"].Value ); // 1

        Debug.Log( speakList0[0].Attributes["content"].Value ); // こんにちは
        Debug.Log( speakList0[1].Attributes["content"].Value ); // ありがとう
        Debug.Log( speakList0[2].Attributes["content"].Value ); // さようなら

        Debug.Log( speakList0[0].Attributes["num"].Value ); // 1
        Debug.Log( speakList0[1].Attributes["num"].Value ); // 2
        Debug.Log( speakList0[2].Attributes["num"].Value ); // 3

        Debug.Log( speakList1[0].Attributes["content"].Value ); // あーい
        Debug.Log( speakList1[1].Attributes["content"].Value ); // ふーい 
        Debug.Log( speakList1[2].Attributes["content"].Value ); // ねむい

        Debug.Log( speakList1[0].Attributes["num"].Value ); // 4
        Debug.Log( speakList1[1].Attributes["num"].Value ); // 5 
        Debug.Log( speakList1[2].Attributes["num"].Value ); // 6
    }
}

さらに細かい使い方は下記URLを参考にしよう。

System.Xml 名前空間 ()
http://msdn.microsoft.com/ja-jp/library/System.Xml(v=vs.100).aspx

23
23
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
23
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?