unity内创建、读取xml文件

在unity的streamingAssets文件夹下创建xml

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Xml;

public class SaveIPAndPort : MonoBehaviour
{
    private string ipAddress = "127.0.0.1";
    private int port = 8888;
    string filePath = Application.streamingAssetsPath + "/config.xml";

    void Start()
    {
        //判断文件是否存在
        if (!File.Exists(filePath))
        {
            SaveToXML();
        }
    }

    void SaveToXML()
    {
        XmlDocument xmlDoc = new XmlDocument();
        XmlElement rootNode = xmlDoc.CreateElement("Config");
        xmlDoc.AppendChild(rootNode);

        XmlElement ipNode = xmlDoc.CreateElement("IP");
        ipNode.InnerText=ipAddress;
        rootNode.AppendChild(ipNode);

        XmlElement portNode = xmlDoc.CreateElement("Port");
        portNode.InnerText=port.ToString();
        rootNode.AppendChild(portNode);

        xmlDoc.Save(filePath);
    }
}

 

读取streamingAssets文件夹下的config.xml文件

using System.Xml;
using UnityEngine;

public class Duq: MonoBehaviour
{
    private string ipAddress;
    private int port;

    void Start()
    {
        ReadFromXML();
        Debug.Log("IP地址:"+ipAddress);
        Debug.Log("端口号:"+port);
    }

    void Update()
    {
        
    }

    void ReadFromXML()
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(Application.streamingAssetsPath + "/config.xml");

        XmlNodeList ipNodes = xmlDoc.GetElementsByTagName("IP");
        XmlNodeList portNodes = xmlDoc.GetElementsByTagName("Port");

        if (ipNodes.Count > 0 && portNodes.Count > 0)
        {
            ipAddress = ipNodes[0].InnerText;
            port = int.Parse(portNodes[0].InnerText);
            Debug.Log("IP Address: " + ipAddress + ", Port: " + port);
        }
        else
        {
            Debug.LogError("Failed to read IP address and port from XML file.");
        }
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值