Unity3D读取XML文件里面的属性

发表于2018-09-03
评论0 3.4k浏览
之前给大家介绍过Unity读取XML、JSON文件的方法,而本篇要再深入一下, 给大家介绍的是读取XML文件里面的属性,不清楚的可以看看。

Mono.xml下载链接:http://download.csdn.net/detail/cwqcwk1/7105071  
<?xml version="1.0"?>
<info>
    <book id="b1" lang="en">
        <name>c++</name>
        <price>570</price>
    </book>
    <book id="b2" lang="en">
        <name>c#</name>
        <price>110</price>
    </book>
</info>

Unity3D读取XML文件里面的属性
using Mono.Xml;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security;
using System.Xml;
using UnityEngine;
public class ReadXML : MonoBehaviour {
    // Use this for initialization
    void Start () {
        //TextAsset ta = Resources.Load("test", typeof(TextAsset)) as TextAsset;
        //ReadXMlTest(new MemoryStream(ta.bytes));
        StartCoroutine(StartTxt());
    }
    // Update is called once per frame
    void Update () {
    }
    IEnumerator StartTxt()
    {
        WWW www = new WWW("file://" + Application.streamingAssetsPath + "/test.xml");
        yield return www;
        //ReadXMlTest(new MemoryStream(www.bytes));
        ReadXMLMono(www.text);
        www.Dispose();
    }
    void ReadXMlTest(Stream stream)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(stream);
        XmlNode info = xmldoc.SelectSingleNode("info");
        foreach (XmlNode node in info.ChildNodes)
        {
            string id = node.Attributes["id"].Value;
            string lang = node.Attributes["lang"].Value;
            string name = node.SelectSingleNode("name").InnerText;
            string price = node.SelectSingleNode("price").InnerText;
            Debug.Log("node.Name:" + node.Name + " id:"+ id + " lang:" + lang + " name:" + name + " price:" + price);
        }
    }
    void ReadXMLMono(string text)
    {
        SecurityParser sp = new SecurityParser();
        sp.LoadXml(text);
        SecurityElement se = sp.ToXml();
        foreach (SecurityElement sel in se.Children)
        {
            string id = (string)sel.Attributes["id"];
            string lang = (string)sel.Attributes["lang"];
            string name = "", price = "";
            foreach (SecurityElement se2 in sel.Children)
            {
                if (se2.Tag == "name")
                {
                    name = se2.Text;
                }
                else if (se2.Tag == "price")
                {
                    price = se2.Text;
                }
            }
            Debug.Log(" id:" + id + " lang:" + lang + " name:" + name + " price:" + price);
        }
    }
}

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引

标签: