Unity 基础 XML文件解析

Unity 基础 XML文件解析


test.xml文件


	
		三国演义
		罗贯中
	

	
		水浒传
		施耐庵
	

	
		红楼梦
		曹雪芹
	

	
		西游记
		吴承恩
	


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 frame
	void Update () {
	
	}

    void Awake()
    {
        loadXML();
    }
}

运行结果:
Unity 基础 XML文件解析_第1张图片

你可能感兴趣的:(Unity基础)