본문 바로가기

프로그램/유니티 스크립트 소스

[유니티 스크립트 소스] XML Loader

728x90
반응형
using System.Xml.Serialization;
using System.IO;
using UnityEngine;

[XmlRoot("XmlRoot_")]
public class XmlElements
{
    [XmlElement("XmlElement1")]
    public string xmlElement1;
    [XmlElement("XmlElement2")]
    public string xmlElement2;
    [XmlElement("XmlElement3s")]
    public XmlElement3s xmlElement3s;
}

public class XmlElement3s
{
    [XmlElement("XmlElement3_1")]
    public string xmlElement3_1;
    [XmlElement("XmlElement3_2")]
    public int xmlElement3_2;
}


public class Demo : MonoBehaviour
{
    public string m_FileName;

    void Start()
    {
        XmlElements xElements = LoadXml(m_FileName);

        Debug.Log($"xElements.xmlElement1 : {xElements.xmlElement1}");
        Debug.Log($"xElements.xmlElement2 : {xElements.xmlElement2}");
        Debug.Log($"xElements.xmlElement2 : {xElements.xmlElement3s.xmlElement3_1}");
        Debug.Log($"xElements.xmlElement2 : {xElements.xmlElement3s.xmlElement3_2}");
    }

    XmlElements LoadXml(string fileName)
    {
        string filePath = Path.Combine(Application.streamingAssetsPath, fileName);

        using (var reader = new StreamReader(filePath))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(XmlElements));

            return (XmlElements)serializer.Deserialize(reader);
        }
    }
}

 

<?xml version="1.0" encoding="utf-8"?>
<XmlRoot_ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                      xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <XmlElement1>Xml Element 1</XmlElement1> <!-- 주석 -->
  <XmlElement2>Xml Element 2</XmlElement2>
  <XmlElement3s>
    <XmlElement3_1>XmlElement 3 1</XmlElement3_1>
    <XmlElement3_2>32</XmlElement3_2>      
  </XmlElement3s>
</XmlRoot_>

 

728x90
반응형