2022년 9월 5일 월요일

xml 삭제

 





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

public class XMLManager : MonoBehaviour
{

    private static XMLManager instance = null;


    string xmlFileName = "TestXml";
    string path = "XML";


    void Awake()
    {
        if (null == instance)
        {
            //이 클래스 인스턴스가 탄생했을 때 전역변수 instance에 게임매니저 인스턴스가 담겨있지 않다면, 자신을 넣어준다.
            instance = this;

            //씬 전환이 되더라도 파괴되지 않게 한다.
            //gameObject만으로도 이 스크립트가 컴포넌트로서 붙어있는 Hierarchy상의 게임오브젝트라는 뜻이지만,
            //나는 헷갈림 방지를 위해 this를 붙여주기도 한다.
            DontDestroyOnLoad(this.gameObject);
        }
        else
        {
            //만약 씬 이동이 되었는데 그 씬에도 Hierarchy에 GameMgr이 존재할 수도 있다.
            //그럴 경우엔 이전 씬에서 사용하던 인스턴스를 계속 사용해주는 경우가 많은 것 같다.
            //그래서 이미 전역변수인 instance에 인스턴스가 존재한다면 자신(새로운 씬의 GameMgr)을 삭제해준다.
            Destroy(this.gameObject);
        }
    }

    public static XMLManager Instance
    {
        get
        {
            if (null == instance)
            {
                return null;
            }
            return instance;
        }
    }


    // Resources/XML/TestItem.XML 파일.
   


    public List<string> LoadComments(string _fileName)
    {
        string pullpath = path + "/" + _fileName;
        TextAsset txtAsset = (TextAsset)Resources.Load(pullpath);
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(txtAsset.text);
        List<string> results = new List<string>();
        XmlNodeList all_nodes = xmlDoc.SelectNodes("dataroot/Comment");

        foreach (XmlNode node in all_nodes)
        {
            results.Add(node.SelectSingleNode("type").InnerText + "_" + node.SelectSingleNode("desc").InnerText);
        }

        return results;
    }


    public List<RoadInfo> LoadRoadInfos()
    {
        string pullpath = path + "/" + "RoadList";
        TextAsset txtAsset = (TextAsset)Resources.Load(pullpath);
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(txtAsset.text);
        List<RoadInfo> results = new List<RoadInfo>();
        XmlNodeList all_nodes = xmlDoc.SelectNodes("RoadXml/Road");

        foreach (XmlNode node in all_nodes)
        {
            RoadInfo temp = new RoadInfo();
            temp.roadName = node.SelectSingleNode("roadName").InnerText;
            temp.posX = node.SelectSingleNode("posX").InnerText;
            temp.posY = node.SelectSingleNode("posY").InnerText;
           

            results.Add(temp);
        }

        Debug.Log("count" + results.Count);

        return results;
    }


    public void LoadXML(string _fileName)
    {
        string pullpath = path + "/" + _fileName;
        TextAsset txtAsset = (TextAsset)Resources.Load(pullpath);
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(txtAsset.text);

        // 하나씩 가져오기 테스트 예제.
        XmlNodeList cost_Table = xmlDoc.GetElementsByTagName("cost");
        foreach (XmlNode cost in cost_Table)
        {
            Debug.Log("[one by one] cost : " + cost.InnerText);
        }

        // 전체 아이템 가져오기 예제.
        XmlNodeList all_nodes = xmlDoc.SelectNodes("dataroot/TestItem");
        foreach (XmlNode node in all_nodes)
        {
            // 수량이 많으면 반복문 사용.
            Debug.Log("[at once] id :" + node.SelectSingleNode("id").InnerText);
            Debug.Log("[at once] name : " + node.SelectSingleNode("name").InnerText);
            Debug.Log("[at once] cost : " + node.SelectSingleNode("cost").InnerText);

            ///한번더 돌리고싶을때
            //foreach (XmlElement element in node)
            //{
            //    Debug.Log(element.InnerText);
            //}


        }

    }

    public void Add_New_Road(RoadInfo _roadInfo)
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(GetPath("RoadList.xml"));

        Add_New_Road_Eelement(xmlDoc, _roadInfo);
        xmlDoc.Save(GetPath("RoadList.xml"));
    }

    public void Add_New_Road_Eelement(XmlDocument xmlDoc, RoadInfo _roadInfo)
    {

        XmlNode newNode;
        XmlElement roadElement = xmlDoc.CreateElement("Road"); //엘리멘트를 만든다~

        XmlElement roadName = xmlDoc.CreateElement("roadName");
        XmlElement posX = xmlDoc.CreateElement("posX");
        XmlElement posY = xmlDoc.CreateElement("posY");




        roadName.InnerText = _roadInfo.roadName;
        posX.InnerText = _roadInfo.posX;
        posY.InnerText = _roadInfo.posY;

        roadElement.AppendChild(roadName);
        roadElement.AppendChild(posX);
        roadElement.AppendChild(posY);


        newNode = xmlDoc.SelectSingleNode("RoadXml");
        newNode.AppendChild(roadElement);
    }


    #region 노말함수
    string GetPath(string fileName)
    {
        string path = "";

        if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
            //path = Application.dataPath.Substring(0, Application.dataPath.Length - 5);
            //path = path.Substring(0, path.LastIndexOf('/'));
            //Read(Path.Combine(Path.Combine(path, "Documents"), "Dialogue.xml"));
            path = Path.Combine(Path.Combine(Application.persistentDataPath, "Documents"), fileName);
        }
        else if (Application.platform == RuntimePlatform.Android)
        {
            path = Path.Combine(Application.persistentDataPath, fileName);
        }
        else
        {
            ///실제 할때는 여기로 해야 모바일에서 된다(원본)
            //path = Path.Combine(Application.persistentDataPath, fileName);
            path = Path.Combine(Application.dataPath + "/Resources/XML/", fileName);

        }

        return path;
    }


    public void DeleteXmlInformation(string xmlFilePath,string deleteElementName)
    {
        try
        {

            Debug.Log("DeleteXmlInformation !!!");

            string pullpath = GetPath(xmlFilePath);

           

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(pullpath);
            XmlNode FirstNode = xmlDoc.DocumentElement;

            foreach (XmlNode Node in FirstNode.SelectNodes(deleteElementName))
            {
                //XmlNode delNode = Node.SelectSingleNode(deleteElementName);
                FirstNode.RemoveChild(Node);
            }

            //XmlNode delNode = FirstNode.SelectSingleNode(deleteElementName);
            //Debug.Log("delNode" + delNode.InnerText);


           

            xmlDoc.Save(GetPath(xmlFilePath));
        }
        catch (Exception ex)
        {
            Debug.Log(ex.ToString());
        }
    }

    #endregion

}

댓글 없음:

댓글 쓰기

git rejected error(feat. cherry-pick)

 문제 아무 생각 없이 pull을 받지않고 로컬에서 작업! 커밋, 푸시 진행을 해버렷다. push에선 remote와 다르니 당연히 pull을 진행해라고 하지만 로컬에서 작업한 내용을 백업하지 않고 진행하기에는 부담스럽다(로컬작업 유실 가능성) 해결하려...