2016. 3. 3. 14:25


안녕하세요.


xml데이터를 만들어야하는데, 손으로 일일히 메모장에 전체를 적을수는 없으니..


제일 간단한 엑셀로 만드는법을 적어보겠습니다.


제일 먼저 엑셀로 만들기 위하면 스키마를 작성해주어야 하는데요


스키마 작성은 노트패드(메모장 또는 기타등등)을 열어서 다음과 같이 적습니다.


한국어, 영어, 중국어 3개로 로컬라이징을 하기위한 언어 스키마입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="UTF-8"?>
<root>
             <texts>                           
                           <index/>
                           <menu/>
                           <kor/>
                           <eng/>
                           <chi/>
             </texts>
             <texts>                           
                           <index/>
                           <menu/>
                           <kor/>
                           <eng/>
                           <chi/>
             </texts>
</root>
cs

꼭 texts는 마음대로 변경하셔도 되지만, 스키마에 한글을 적으시면 안됩니다.

그리고 반복된다는것을 알리기위해 꼭 2번 적어야합니다.


자 이렇게 작성했다면, 이를 저장합니다.


단, 저장시 확장자명을 .xml로 저장해주셔야합니다.


자 이제 엑셀을 켜봅시다.


먼저 엑셀의 개발도구를 열어야하는데요.


개발도구를 왼쪽 리본의서 메뉴에서 설정가능합니다..


모르면 구글링하면 친절한 블로그들이 있을꺼애요



개발도구에서 원본을 클릭합시다.



그러면 우측에  XML원본이라는 창이 뜰텐데요.

 그밑에 XML맵을 누르면 다음과 같은 창이 뜹니다.



그러면 밑에 추가를 누르신후 아까 저장한 xml파일을 눌러 줍시다.

그럼 다음과 같은 경고창이 하나 뜰텐데. 바로 확인 눌러줍니다.



그러면 아까 만든 맵이 이곳에 이렇게 뜰꺼애요! 아까 적은 글자 대로 뜰껍니다. 그럼 확인을 누릅시다.



그럼 우측에 다음과 같이 생성된걸 볼수있습니다.


그럼 위에 데이터를 넣기위해 간단하게 엑셀에 데이터를 적어봅시다.


첫줄은 아무상관없으니, 적기 편하게 구분을 지어주시고, 그다음부터 데이터를 적어나가면 됩니다.



자 저는 이렇게 적었어요. 정말 간단하죠?


그다음 첫열 즉 A열을 전부 드래그 한후 우측의 인덱스를 더블클릭합니다.


그러면 값들이 알아서 매핑됩니다.


이처럼 말이죠.


그럼 남은 값들도 전부 매핑 해봅시다.



자 이제 저장만 하면 됩니다.


주의할점은 엑셀로 저장하는것이 아닌 xml로 저장하는겁니다.


역시 저장할때 경고창이 뜰텐데 무시하고 저장합시다.


(나중에 수정을 하려면 엑셀파일로도 저장해두는게 좋아요, 어차피 스키마는 유지됩니다.)


그리고 저장한 파일을 열어보면

짜잔, 다음과같이 값이 알맞게 매핑되어 저장된것을 볼수있습니다.

Posted by 시리시안
2016. 2. 29. 16:11
XML만들기는 다음 포스팅을 확인해주세요


이미 만들어진 XML은 다음과 같은 코드로 불러올수있습니다.
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using UnityEngine;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Text;
using System.Collections.Generic;
/**
@date 2016/02/29
@author 조원우(jjgaa2@naver.com)
@brief App에서 관리해야하는 모든 텍스트를, 처음에 XMl파일을 읽어와 알맞은 텍스트를 반환합니다.
*/
public class TextManager : MonoBehaviour
{
 
    void Awake()
    {
        LoadingText();
    }
 
    List<LocalWord> AllText = new List<LocalWord>();    ///< 이곳에 모든 Text가 쌓입니다.
    /**
@brief 변수 AllText에 xml로 만들어진 데이터를 불러와 짚어 넣습니다.
*/
    void LoadingText()
    {
        TextAsset textAsset = (TextAsset)Resources.Load("Texts");
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.LoadXml(textAsset.text);
        //xml생성
        XmlNodeList Index_Table = xmldoc.GetElementsByTagName("index");
        XmlNodeList menu_Table = xmldoc.GetElementsByTagName("menu");
        XmlNodeList kor_Table = xmldoc.GetElementsByTagName("kor");
        XmlNodeList eng_Table = xmldoc.GetElementsByTagName("eng");
        XmlNodeList chi_Table = xmldoc.GetElementsByTagName("chi");
        for (int i = 0; i < Index_Table.Count; i++)
        {
            LocalWord mWord = new LocalWord();
            mWord.Index = System.Convert.ToInt32(Index_Table[i].InnerText);
            mWord.kor = kor_Table[i].InnerText;
            mWord.eng = eng_Table[i].InnerText;
            mWord.chi = chi_Table[i].InnerText;
            AllText.Add(mWord);
        }
    }
 
    public enum Enum_Language { kor, eng, chi };
    public Enum_Language Language = Enum_Language.kor;
 
    public string GetLocalizingText(int Index)
    {
        if (AllText[Index].Index == Index)
        {
            switch (Language)
            {
                case Enum_Language.kor:
                    return AllText[Index].kor;
                case Enum_Language.eng:
                    return AllText[Index].eng;
                case Enum_Language.chi:
                    return AllText[Index].chi;
            }
        }
        for (int i = 0; i < AllText.Count; i++)
        {
            if (AllText[i].Index == Index)
            {
                switch (Language)
                {
                    case Enum_Language.kor:
                        return AllText[Index].kor;
                    case Enum_Language.eng:
                        return AllText[Index].eng;
                    case Enum_Language.chi:
                        return AllText[Index].chi;
                }
            }
        }
 
        Debug.Log("[Error] 반환된 Text가 없습니다.");
        return "[Error] 반환된 Text가 없습니다.";
    }
 
}
 
/**
@date 2016/02/29
@author 조원우(jjgaa2@naver.com)
@brief 텍스트 데이터 클래스.    
*/
public class LocalWord
{
    public int Index;
    public string kor;
    public string eng;
    public string chi;
}
 
 
cs

.



Posted by 시리시안
2016. 2. 22. 05:30

this post shows asimple tutorial to do some basic operations with xml file on Unity3D using C#.

How to load?

Put an XML file on Resources folder and load itwith Resources class from Unity3D
xml sample:

<achievement>

 <uniqueid>0</uniqueid>

 <referencename>MyAchievement</referencename>

 <goal>Solve until 10seconds</goal>

 <points>10</points>

</achievement>

 

using UnityEngine;

using System.Collections;

using System.Xml;

 

 

public class XMLEditor : MonoBehaviour

{

 

   void Awake()

    {

       //Load

       TextAsset textXML = (TextAsset)Resources.Load("myxml.xml",typeof(TextAsset));

       XmlDocument xml = new XmlDocument();

       xml.LoadXml(textXML.text);

    }

}

Yeah! Using a TextAsset you can make it very simply!

How to read?

Pretty simple! Use .NET framework, XmlDocumentwill turn you live more easy.

using UnityEngine;

using System.Collections;

using System.Xml;

 

 

public class XMLEditor : MonoBehaviour

{

   void Awake()

    {

       //Load

       TextAsset textXML = (TextAsset)Resources.Load("myxml.xml",typeof(TextAsset));

       XmlDocument xml = new XmlDocument();

       xml.LoadXml(textXML.text);

 

       //Read

       XmlNode root = xml.FirstChild;

       foreach(XmlNode node in root.ChildNodes)

       {

           if (node.FirstChild.NodeType == XmlNodeType.Text)

                Debug.Log(node.InnerText);

       }

    }

}


Ok, but if there are multiplehierarchies you will must implement your own ReadMethod to do that bynavigating for all nodes.

How to save?

using UnityEngine;

using System.Collections;

using System.Xml;

 

 

public class XMLEditor : MonoBehaviour

{

   void Awake()

    {

       //Load

       TextAsset textXML = (TextAsset)Resources.Load("myxml.xml",typeof(TextAsset));

       XmlDocument xml = new XmlDocument();

       xml.LoadXml(textXML.text);

 

       //Read

       XmlNode root = xml.FirstChild;

        foreach(XmlNode node in root.ChildNodes)

       {

           if (node.FirstChild.NodeType == XmlNodeType.Text)

                node.InnerText ="none";

       }

 

       //Simple Save

       xml.Save(AssetDatabase.GetAssetPath(textXML));

    }

}

The easy way! :)



출처 : http://fernandogamedev-en.blogspot.kr/2012/09/how-to-load-read-and-save-xml-on-unity3d.html

Posted by 시리시안
2016. 2. 19. 15:55

Save and Load Info to XML

This script will allow you to save and load data about an object into an XML file. To use, add an empty game object to the scene and attache the script to the object. Change the Player on that game object property to the item you wish to save properties about. When you start the scene, you will see a save and load button, these allow you to save and load the information from the xml file. The guts of what you save is located in the UserData class, change this as you see fit to allow you to save what you want. You will also need to update the save method to store the information that you are looking to store. At the moment, the code is only setup to store the postition of the object in world space.


===========================================================================

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
using UnityEngine;
using System.Collections; 
using System.Xml; 
using System.Xml.Serialization; 
using System.IO; 
using System.Text; 
 
public class
_GameSaveLoad: MonoBehaviour { 
 
// An example where the encoding can be found is at   
//http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp   
// We will just use the KISS method and cheat a little and use 
// the examples from the web page since they are fully described 
// This is our local
private members 
  
Rect _Save, _Load, _SaveMSG, _LoadMSG;  
bool _ShouldSave, _ShouldLoad,_SwitchSave,_SwitchLoad;   
string _FileLocation,_FileName; 
public GameObject _Player; 
UserData myData; 
string _PlayerName; 
string _data;  
Vector3 VPosition; 
// When the EGO is
instansiated the Start will trigger 
// so we setup our
initial values for our local members 
void Start () { 
// We setup our
rectangles for our messages 
_Save=new Rect(10,80,100,20); 
_Load=new Rect(10,100,100,20);    
_SaveMSG=new Rect(10,120,400,40); 
_LoadMSG=new Rect(10,140,400,40);       
// Where we want to save and load to and from 
_FileLocation=Application.dataPath;      
_FileName="SaveData.xml";       
// for now, lets just set the name to Joe Schmoe      
_PlayerName = "Joe Schmoe"
// we need soemthing to store the information into 
myData=new UserData();  
 
void Update () {}    
void OnGUI()   
{      
//***************************************************  
// Loading The Player...   
//
**************************************************       
 if (GUI.Button(_Load,"Load")) {       
GUI.Label(_LoadMSG,"Loading from: "+_FileLocation); 
 
// Load our UserData into myData      
LoadXML();      
if(_data.ToString() != "")  
{        
// notice how I use a reference to type (UserData) here, you need this        
// so that the returned object is converted into the correct type        
myData = (UserData)DeserializeObject(_data);  
// set the players
position to the data we loaded        
VPosition=new Vector3(myData._iUser.x,myData._iUser.y,myData._iUser.z);              
_Player.transform.position=VPosition;       
// just a way to show that we loaded in ok        
Debug.Log(myData._iUser.name);      
}   
}   
//***************************************************   
// Saving The Player...   
//
**************************************************      
if (GUI.Button(_Save,"Save")) {     
GUI.Label(_SaveMSG,"Saving to: "+_FileLocation);   
myData._iUser.x=_Player.transform.position.x;     
myData._iUser.y=_Player.transform.position.y;     
myData._iUser.z=_Player.transform.position.z;     
myData._iUser.name=_PlayerName;       
// Time to creat our XML! 
     _data = SerializeObject(myData); 
     // This is the final resulting XML from the serialization process 
     CreateXML();      
     Debug.Log(_data);
   }      } 
 
 
   /* The following
metods came from the referenced URL */ 
   string UTF8ByteArrayToString(byte[] characters) 
   {      
      UTF8Encoding encoding = new UTF8Encoding(); 
      string constructedString = encoding.GetString(characters); 
      return (constructedString); 
   } 
   byte[] StringToUTF8ByteArray( string pXmlString) 
   { 
      UTF8Encoding encoding = new UTF8Encoding(); 
      byte[] byteArray = encoding.GetBytes(pXmlString); 
      return byteArray; 
   }  
   // Here we serialize our UserData object of myData 
   string SerializeObject(object pObject) 
   { 
      string XmlizedString = null
      MemoryStream memoryStream = new MemoryStream(); 
      XmlSerializer xs = new XmlSerializer(typeof(UserData)); 
      XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); 
      xs.Serialize(xmlTextWriter,pObject); 
      memoryStream = (MemoryStream)xmlTextWriter.BaseStream; 
      XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray()); 
      return XmlizedString; 
   }  
   // Here we deserialize it back into its original form 
   object DeserializeObject(string pXmlizedString) 
   { 
      XmlSerializer xs = new XmlSerializer(typeof(UserData)); 
      MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString)); 
      XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); 
      return xs.Deserialize(memoryStream); 
   }  
   // Finally our save and load methods for the file itself 
   void CreateXML() 
   { 
      StreamWriter writer; 
      FileInfo t = new FileInfo(_FileLocation+"\\"+ _FileName); 
      if(!t.Exists) 
      { 
         writer = t.CreateText(); 
      } 
      else 
      { 
         t.Delete(); 
         writer = t.CreateText(); 
      } 
      writer.Write(_data); 
      writer.Close(); 
      Debug.Log("File written."); 
   }  
   void LoadXML() 
   { 
      StreamReader r = File.OpenText(_FileLocation+"\\"+ _FileName); 
      string _info = r.ReadToEnd(); 
      r.Close(); 
      _data=_info; 
      Debug.Log("File Read"); 
   } 
// UserData is our custom class that holds our defined objects we want to store in XML format 
 public class UserData 
 { 
    // We have to define a default instance of the structure 
   public DemoData _iUser; 
    // Default constructor doesn't really do anything at the moment 
   public UserData() { } 
   // Anything we want to store in the XML file, we define it here 
 
   public struct DemoData 
   { 
      public float x; 
      public float y; 
      public float z; 
      public string name; 
   } 
}
 
 
 
 
cs
출처

http://wiki.unity3d.com/index.php?title=Save_and_Load_from_XML


Posted by 시리시안