C# XML创建和解析

本文介绍了一个使用Unity进行XML文件创建、更新、添加及解析的示例代码。通过具体的代码实现,展示了如何利用C#在Unity环境中操作XML文件,包括初始化XML结构、更新属性值、新增节点以及读取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

xml和json都是常用的数据存储方式,先保存下来,以后忘了直接用。。。

using System.IO;
using System.Text;
using System.Xml;
using UnityEngine;
using System.Collections;

public class XMLApply: MonoBehaviour
{

    public string fileName = "Books.xml";

    private void Start()
    {
        //CreateXML();

        //UpdateXml();

        //AddXml();

        ParseXML();
    }


    /// <summary>
    /// 创建XML文件
    /// </summary>
    public void CreateXML()
    {
        string filePath = Application.dataPath + "./" + fileName;

        if (!File.Exists(filePath))
        {
            XmlDocument BooksXML = new XmlDocument();

            XmlElement myFavoriteBooks = BooksXML.CreateElement("MyFavoriteBooks");
            XmlElement history = BooksXML.CreateElement("History");
            history.SetAttribute("year", "2013");
            XmlElement item_empireOfQing = BooksXML.CreateElement("item");
            item_empireOfQing.SetAttribute("name", "大秦帝国");
            item_empireOfQing.SetAttribute("price", "100");
            item_empireOfQing.InnerText = "Sara";

            XmlElement item_theLastMan = BooksXML.CreateElement("item");
            item_theLastMan.SetAttribute("name", "麦田的守望者");
            item_theLastMan.SetAttribute("price", "70");
            item_theLastMan.InnerText = "Lisa";

            XmlElement item_worldHistory = BooksXML.CreateElement("item");
            item_worldHistory.SetAttribute("name", "世界历史");
            item_worldHistory.SetAttribute("price", "40");
            item_worldHistory.InnerText = "Michael";

            XmlElement software = BooksXML.CreateElement("SOftware");
            XmlElement item_php = BooksXML.CreateElement("PHP");
            item_php.SetAttribute("name", "php");
            item_php.SetAttribute("price", "35");
            item_php.InnerText = "KD";

            history.AppendChild(item_empireOfQing);
            history.AppendChild(item_theLastMan);
            history.AppendChild(item_worldHistory);
            software.AppendChild(item_php);
            myFavoriteBooks.AppendChild(history);
            myFavoriteBooks.AppendChild(software);
            BooksXML.AppendChild(myFavoriteBooks);
            
            BooksXML.Save(filePath);

            Debug.Log("XML file create success.....");
        }
    }



    /// <summary>
    /// 更新xml文件内容
    /// </summary>
    public void UpdateXml()
    {
        string filePath = Application.dataPath + "/" + fileName;

        if (File.Exists(filePath))
        {
            //create a xml reference
            XmlDocument BooksXML = new XmlDocument();
            //read exists file into BooksXML
            BooksXML.Load(filePath);

            XmlNodeList nodeList = BooksXML.SelectSingleNode("MyFavoriteBooks").ChildNodes;

            foreach (XmlElement node in nodeList)
            {
                if (node.GetAttribute("year") == "2013")
                {
                    node.SetAttribute("year", "2014");

                    XmlNodeList subNodeList = node.ChildNodes;

                    foreach (XmlElement subNode in subNodeList)
                    {
                        subNode.InnerText += "Updated...";
                    }

                    break;
                }
            }

            BooksXML.Save(filePath);
            Debug.Log("Update success...");
        }
        
    }


    /// <summary>
    /// 在现有xml文件中,增加一个节点
    /// </summary>
    public void AddXml()
    {
        string filePath = Application.dataPath + "/" + fileName;

        if (File.Exists(filePath))
        {
            XmlDocument BooksXML = new XmlDocument();
            BooksXML.Load(filePath);

            XmlNode root = BooksXML.SelectSingleNode("MyFavoriteBooks");
            XmlElement culture = BooksXML.CreateElement("Culture");
            culture.SetAttribute("year", "2012");

            XmlElement item_China = BooksXML.CreateElement("item");
            item_China.SetAttribute("name", "中国文化");
            item_China.SetAttribute("price", "30");
            item_China.InnerText = "rechard";

            culture.AppendChild(item_China);
            root.AppendChild(culture);
            BooksXML.AppendChild(root);
            BooksXML.Save(filePath);

            Debug.Log("Add node success...");
        }
    }


    /// <summary>
    /// 解析xml文件
    /// </summary>
    public void ParseXML()
    {
        string filePath = Application.dataPath + "/" + fileName;
        StringBuilder booksInfo = new StringBuilder("");

        XmlDocument BooksXML = new XmlDocument();
        BooksXML.Load(filePath);

        XmlNode rootNode = BooksXML.FirstChild;

        if (rootNode.Name == "MyFavoriteBooks")
        {
            XmlNodeList nodeList = rootNode.ChildNodes;

            foreach (XmlElement node in nodeList)
            {
                booksInfo.Append(node.Name + "\n");

                foreach (XmlElement subNode in node.SelectNodes("item"))
                {
                    booksInfo.Append("\t " + subNode.GetAttribute("name") + "   , price:" + subNode.GetAttribute("price") + "\n");
                }

                booksInfo.Append("\n");
            }

            Debug.Log(booksInfo.ToString());
        }
        else
        {
            Debug.Log("YOU LOAD WRONG FILE....");
        }

    }
}


附上一张图:



这里不容错过。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值