2014년 5월 8일 목요일

xml 파싱

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class XmlParsing : MonoBehaviour {

public Dictionary<int, RoomInfo> dictRI = new Dictionary<int, RoomInfo>();

// Use this for initialization
void Start () {
WriteXML();
ReadXML();
}

void WriteXML()
{
RoomInfo ri = new RoomInfo();
ri.id = 1;
ri.byteB = 1;
ri.stringS = "aaa";
ri.boolB = false;

dictRI.Add(ri.id, ri);

ri = new RoomInfo();

ri.id = 2;
ri.byteB = 2;
ri.stringS = "bbb";
ri.boolB = true;

dictRI.Add(ri.id, ri);

DataControl.i.WriteRoomInfo(dictRI, "RoomInfo.xml");
}

void ReadXML()
{
dictRI.Clear();

dictRI = DataControl.i.ReadRoomInfo("RoomInfo.xml");
foreach(RoomInfo ri in dictRI.Values)
{
Debug.Log ("id : " + ri.id + ", byte : " + ri.byteB + ", string : " + ri.stringS + ", bool : " + ri.boolB);
}
}


}

데이터 컨트롤...

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Text;
using System.Xml.XPath;

public class DataControl : MonoBehaviour {

public static DataControl i;

void Awake()
{
i = this;
}


/* 방 정보 리스트를 전달하는 함수이다. */
public Dictionary<int, RoomInfo> ReadRoomInfo(string URI)
{
Dictionary<int, RoomInfo> dictRI = new Dictionary<int, RoomInfo>();

//TextAsset ta = Resources.Load (URI) as TextAsset;
string strXML = readStringFromFile(URI);
Debug.Log (strXML);


XmlDocument xmlDoc = new XmlDocument(); // xmlDoc is the new xml document.
// xmlDoc.LoadXml(ta.text); // load the file.
xmlDoc.LoadXml(strXML); // load the file.
XmlNodeList rooms = xmlDoc.GetElementsByTagName("RoomInfo"); // get StagePattern[]

foreach(XmlNode room in rooms)
{
XmlNodeList roomContent = room.ChildNodes;

RoomInfo ri = new RoomInfo();

foreach(XmlNode roomItem in roomContent) // pattern nodes.
{
if(roomItem.Name == "id") ri.id = XmlConvert.ToInt32(roomItem.InnerText);
if(roomItem.Name == "byteB") ri.byteB = XmlConvert.ToByte(roomItem.InnerText);
if(roomItem.Name == "stringS") ri.stringS = roomItem.InnerText;
if(roomItem.Name == "boolB") ri.boolB = XmlConvert.ToBoolean(roomItem.InnerText);
}

if( !dictRI.ContainsKey(ri.id) )
{
dictRI.Add(ri.id, ri);
}
}

return dictRI;
}

/* The following metods came from the referenced URL */
public string UTF8ByteArrayToString(byte[] characters)
{    
UTF8Encoding encoding = new UTF8Encoding();
string constructedString = encoding.GetString(characters);
return (constructedString);
}

public string SerializeObject<T>(T obj)
{
try
{
string xmlString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(T));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, obj);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
xmlString = UTF8ByteArrayToString(memoryStream.ToArray());    
return xmlString;
}
catch
{
return string.Empty;
}
}

public void WriteRoomInfo(Dictionary<int, RoomInfo> dictRI, string path)
{
try
{
List<RoomInfo> listRI = new List<RoomInfo>();
listRI.AddRange(dictRI.Values);
string myXML = SerializeObject<List<RoomInfo>>(listRI);

File.WriteAllText(path, myXML);
}
catch
{
Debug.LogError ("XML Convert Error! : WriteRoomInfo");
}
}

public string readStringFromFile( string filename)//, int lineIndex )
{
#if !WEB_BUILD
string path = pathForDocumentsFile( filename );

if (File.Exists(path))
{
FileStream file = new FileStream (path, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader( file );

string str = null;
str = sr.ReadLine ();

sr.Close();
file.Close();

return str;
}

else
{
return null;
}
#else
return null;
#endif
}

public string pathForDocumentsFile( string filename )
{
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
string path = Application.dataPath.Substring( 0, Application.dataPath.Length - 5 );
path = path.Substring( 0, path.LastIndexOf( '/' ) );
return Path.Combine( Path.Combine( path, "Documents" ), filename );
}

else if(Application.platform == RuntimePlatform.Android)
{
string path = Application.persistentDataPath;
path = path.Substring(0, path.LastIndexOf( '/' ) );
return Path.Combine (path, filename);
}

else
{
string path = Application.dataPath;
path = path.Substring(0, path.LastIndexOf( '/' ) );
return Path.Combine (path, filename);
}
}


}