赞
踩
using System.Collections; using System.Collections.Generic; using System.Xml; using UnityEngine; public class XmlTest : MonoBehaviour { // Use this for initialization void Start () { // ParseXML(); // ParseXML2(); CreateXML(); } //解析xml方法一 void ParseXML() { //xml文档类 XmlDocument doc = new XmlDocument(); //读取xml文档 doc.Load(Application.dataPath+"/Resources/xmldata.xml"); //读取节点或元素 只有一个节点 first和Last都可以用 XmlElement rootEle = doc.LastChild as XmlElement; //studens节点 XmlElement studentsEle = rootEle.FirstChild as XmlElement; //遍历students节点 foreach(XmlElement studentEle in studentsEle.ChildNodes) { //获取ID id是属性,通过属性方法获取 string id = studentEle.GetAttribute("id"); //获取姓名 获取这个表情值 string name = studentEle.ChildNodes[0].InnerText; //获取年龄 string age = studentEle.ChildNodes[1].InnerText; Debug.Log(id+" "+name+" "+age); } } //解析XML方法二 void ParseXML2() { //xml文档类 XmlDocument doc = new XmlDocument(); //读取xml文档 doc.Load(Application.dataPath+"/Resources/xmldata.xml"); //XPath解析方式 路径语法:通用语法,不是为某个数据格式定义的 //root/students/student/name //绝对路径 // //name相对路径 会进行遍历搜索 //结合使用 //students/hero[2]/name 可以直接拿第2个元素从1开始 //[last()-1]获取倒是2个 //[position()<3] 获取前两个 XmlNodeList list = doc.SelectNodes("/root/students/student[last()-1]"); foreach(XmlElement ele in list) { Debug.Log(ele.InnerText);//如果想打印name标签名,用ele.name就可以 } } void CreateXML() { //创建文档类 XmlDocument doc = new XmlDocument(); //创建文档声明 XmlDeclaration dec = doc.CreateXmlDeclaration("1.0","utf-8",""); doc.AppendChild(dec); //root节点 XmlElement rootEle = doc.CreateElement("root"); doc.AppendChild(rootEle); //students节点 XmlElement studentsEle = doc.CreateElement("students"); rootEle.AppendChild(studentsEle); //循环数据 string[] names = new string[]{"小明","小白","小红"}; int[] ages = new int[]{18,19,20}; //循环创建student节点 for(int i=0;i<3;i++) { XmlElement studentEle = doc.CreateElement("student"); studentsEle.AppendChild(studentEle); //name节点 XmlElement nameEle = doc.CreateElement("name"); nameEle.InnerText = names[i]; studentEle.AppendChild(nameEle); //年龄节点 XmlElement ageEle = doc.CreateElement("age"); ageEle.InnerText = ""+ages[i]; studentEle.AppendChild(ageEle); //添加属性 // studentEle.SetAttribute("id",i+""); XmlAttribute att = doc.CreateAttribute("id"); att.Value = i+ ""; studentEle.Attributes.Append(att); } //保存 doc.Save(Application.dataPath + "/Resources/xmldata.xml"); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。