纳金网

标题: unity c#读取xml [打印本页]

作者: 王者再临    时间: 2014-12-31 23:00
标题: unity c#读取xml
  1. using UnityEngine;

  2. using System.Collections;

  3. using System.Xml;

  4. using System.IO;

  5. public class ReadXml : MonoBehaviour {

  6. private string[] myNames;

  7. // Use this for initialization

  8. void Start () {

  9. LoadMyXML();

  10. }

  11. // Update is called once per frame

  12. void Update () {

  13. }

  14. private void LoadMyXML()

  15. {

  16. //xml存放路径

  17. string filePath = Application.dataPath + @“/testxml.xml”;

  18. Debug.Log (“filePath=” + filePath);

  19. if (File.Exists(filePath))

  20. {

  21. //声明个xml文档

  22. XmlDocument xmlDocument = new XmlDocument();

  23. XmlReaderSettings settings = new XmlReaderSettings();

  24. settings.IgnoreComments = true;//忽略文档里面的注释

  25. xmlDocument.Load(XmlReader.Create(filePath,settings));

  26. //获取名称为myRoot的根节点

  27. XmlNodeList xmlNodeList = xmlDocument.SelectSingleNode(“myRoot”).ChildNodes;

  28. //Debug.Log(xmlNodeList.Count);

  29. //遍历子节点

  30. Debug.Log(“readxml”);

  31. foreach (XmlElement xmlElement1 in xmlNodeList)

  32. {

  33. if (xmlElement1.Name == “myChild”)

  34. {

  35. int index = 0;

  36. myNames = new string[xmlElement1.ChildNodes.Count];

  37. //Debug.Log(xmlElement1.ChildNodes.Count);

  38. foreach (XmlElement xmlElement2 in xmlElement1.ChildNodes)

  39. {

  40. myNames[index] = xmlElement2.InnerText;

  41. Debug.Log(myNames[index]);

  42. index++;

  43. }

  44. }

  45. }

  46. }

  47. }

  48. }

  49. xml文件

  50. <?xml version=“1.0” encoding=“UTF-8”?>

  51. <myRoot>

  52. <myChild>

  53. <myName>张三</myName>

  54. <myName>李四</myName>

  55. <myName>王老五</myName>

  56. <myName>刘邦</myName>

  57. <myName>项羽</myName>

  58. <myName>秦始皇</myName>

  59. <!--记录书本的信息-->

  60. </myChild>

  61. </myRoot>
复制代码

作者: tianhett    时间: 2014-12-31 23:24
涨姿势了。。。。。。。。
作者: KISS2015    时间: 2015-1-2 19:22
不错的C#代码
作者: 我不再年轻    时间: 2015-1-3 11:08
不错, 学习了!




欢迎光临 纳金网 (http://go.narkii.com/club/) Powered by Discuz! X2.5