Unity 基础 XML文件解析

来源:互联网 发布:mac finder 编辑:程序博客网 时间:2024/06/05 11:29

Unity 基础 XML文件解析


test.xml文件
<books><book type="四大名著(1)"><name>三国演义</name><author>罗贯中</author></book><book type="四大名著(2)"><name>水浒传</name><author>施耐庵</author></book><book type="四大名著(3)"><name>红楼梦</name><author>曹雪芹</author></book><book type="四大名著(4)"><name>西游记</name><author>吴承恩</author></book></books>

XMLParse.cs文件
using UnityEngine;using System.Collections;using System.Xml;using System.IO;public class XMLParse : MonoBehaviour {// Use this for initialization    XmlDocument xmldoc;    void Start () {                        ParseXML();            }    void loadXML()    {        xmldoc = new XmlDocument();        TextAsset rscTextAsset = Resources.Load("XML/test", typeof(TextAsset)) as TextAsset;        if (rscTextAsset != null)            xmldoc.Load(new MemoryStream(rscTextAsset.bytes));    }    void ParseXML()    {        if (xmldoc != null)        {            XmlNodeList nodeList = xmldoc.SelectSingleNode("books").ChildNodes;            foreach (XmlElement book in nodeList)  //遍历所有子节点,查找小关卡属性            {                if (book.Name == "book")                {                                       //判断book是否包含某种属性                    bool isHaveType = book.HasAttribute("type");                    if (isHaveType)                    {                        //获取 book 节点的指定名称的属性值                        string atri = book.GetAttribute("type");                        Debug.Log("book atri is " + atri);                    }                    //获取book节点下面的子节点                    string bookname = book.GetElementsByTagName("name").Item(0).InnerText;                    Debug.Log("     book name is " + bookname);                    string bookauthor = book.GetElementsByTagName("author").Item(0).InnerText;                    Debug.Log("     book author is " + bookauthor);                }            }        }    }// Update is called once per framevoid Update () {}    void Awake()    {        loadXML();    }}

运行结果:

0 0
原创粉丝点击