레이블이 xml인 게시물을 표시합니다. 모든 게시물 표시
레이블이 xml인 게시물을 표시합니다. 모든 게시물 표시

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

}

2019년 9월 26일 목요일

xml XmlSerializer

<FCE_0004>
  <item>
    <TOPT_ZONE_PT>300</TOPT_ZONE_PT>
    <TOPT_ZONE_PB>300</TOPT_ZONE_PB>
    <TOPT_ZONE_HT>300</TOPT_ZONE_HT>
    <TOPT_ZONE_HB>300</TOPT_ZONE_HB>
    <TOPT_ZONE_ST>300</TOPT_ZONE_ST>
    <TOPT_ZONE_SB>300</TOPT_ZONE_SB>
  </item>
  <item />
  <item>
    <TOPT_ZONE_PT>200</TOPT_ZONE_PT>
    <TOPT_ZONE_PB>200</TOPT_ZONE_PB>
    <TOPT_ZONE_HT>200</TOPT_ZONE_HT>
    <TOPT_ZONE_HB>200</TOPT_ZONE_HB>
    <TOPT_ZONE_ST>200</TOPT_ZONE_ST>
    <TOPT_ZONE_SB>200</TOPT_ZONE_SB>
  </item>
</FCE_0004>


[Serializable]
[XmlRoot("FCE_0004")]
public class FCE_ZONE_0004
{
    [XmlElement("item")]
    public FCE_ZONE_TMP_DATA[] FCE_Zone_Temp;
}


[Serializable]
public class FCE_ZONE_TMP_DATA
{
    [XmlElement("TOPT_ZONE_PT")]
    public float TOPT_ZONE_PT;
    [XmlElement("TOPT_ZONE_PB")]
    public float TOPT_ZONE_PB;
    [XmlElement("TOPT_ZONE_HT")]
    public float TOPT_ZONE_HT;
    [XmlElement("TOPT_ZONE_HB")]
    public float TOPT_ZONE_HB;
    [XmlElement("TOPT_ZONE_ST")]
    public float TOPT_ZONE_ST;
    [XmlElement("TOPT_ZONE_SB")]
    public float TOPT_ZONE_SB;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 
private static T GetDeserialize<T>(byte[] data)
 
    {
 
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
 
        using (MemoryStream ms = new MemoryStream(data))
 
        {
 
            return (T)xmlSerializer.Deserialize(ms);
 
        }
 
    }
 
 
 
public string Serialize<T>(T objectToSerialize)
 
    {
 
        XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType());
 
 
 
        using (StringWriter textWriter = new StringWriter())
 
        {
 
            xmlSerializer.Serialize(textWriter, objectToSerialize);
 
            return textWriter.ToString();
 
        }
 
    }
 
 
cs



FCE_ZONE_0004 test = GetDeserialize<FCE_ZONE_0004>(conv_data);


Debug.Log("Length :" + test.FCE_Zone_Temp.Length);


///select * from table
쿼리 여서 여러줄이 나옴

그 여러줄이 List에 알아서 들어감







2019년 9월 16일 월요일

xml 변수 설정하기

안드로이드 개발할 시 주로 문자열을 string.xml 에서 관리합니다. 그런데 이 문자열 사이에 값이 달라지는 변수를 두고 싶을 때가 있습니다.

String.xml

<string name="hello">%1$s가 %2$s에게 인사합니다.</string> 

 %1$s : string  (문자열 일시)     %1$d : int   (숫자 일시)

JAVA
그리고 자바에서는 아래와 같이 코드를 해줍니다.


Resources res = getResources();

String text = String.format(res.getString(R.string.hello), "아이", "선생님"); 

결과값 -> 아이가 선생님에게 인사합니다.





영어권에서 복수형 단어 처리하기
영문으로 할 때에는 여러개일 경우에는 s가 붙는 거처럼 복수형 형태가 되는 경우가 있습니다.

String.xml


  <plurals name="file">


        
<item quantity="one">One file found.</item>


        
<item quantity="other">%d files found.</item>


    
</plurals>
 

%s : string   (문자열일경우)    %d : int    (숫자일경우)



JAVA

String.format(getResources().getQuantityString(R.plurals.file, 2), 4);
출력-> 4 files found.
String.format(getResources().getQuantityString(R.plurals.file, 1), 4);
출력-> One file found. 

출처: https://jhrun.tistory.com/123 [JHRunning]

git rejected error(feat. cherry-pick)

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