2014-10-12 3 views
-1

(C#을)액세스 및 덮어 쓰기 XML 노드 내가이 XML (이 예를 목적으로 트리밍 된 것) 한

<?xml version="1.0" encoding="utf-8"?> 
<levels> 
    <level><!-- level 1 ! --> 
     <name>Level 1</name> 
     <title>Title 01</title> 
     <crystal01>false</crystal01> 
     <crystal02>false</crystal03> 
     <crystal02label>Label 1</crystal03label> 
     <crystal03>false</crystal04> 
    </level> 
    <level><!-- level 2 ! --> 
     <name>Level 2</name> 
     <title>Title 02</title> 
     <crystal01>true</crystal01> 
     <crystal02>true</crystal03> 
     <crystal02label>Label 2</crystal03label> 
     <crystal03>false</crystal04> 
    </level> 
</levels> 

그리고 난

public class LoadXmlData : MonoBehaviour // the Class 
{ 
    public int actualLevel = 1; 
    static int LevelMaxNumber; 
    static int WaipointCounter = 0; 

    public static string lvlname = ""; 
    public static string lvltitle = ""; 

    public static string crystal01 = ""; 
    public static string crystal02 = ""; 
    public static string crystal02label = ""; 
    public static string crystal03 = ""; 

    public TextAsset XMLData; 

    List<Dictionary<string,string>> levels = new List<Dictionary<string,string>>(); 
    Dictionary<string,string> obj; 


    void Start() 
    { GetLevel(); 
     StartCoroutine(LevelLoadInfo(0.0F)); 
     LevelMaxNumber = levels.Count; 
    } 

    public void GetLevel() 
    { 
     XmlDocument xmlDoc = new XmlDocument(); // xmlDoc is the new xml document. 
     xmlDoc.LoadXml(XMLData.text); // load the file. 
     XmlNodeList levelsList = xmlDoc.GetElementsByTagName("level"); // array of the level nodes. 

     foreach (XmlNode levelInfo in levelsList) 
     { 
      XmlNodeList levelcontent = levelInfo.ChildNodes; 
      obj = new Dictionary<string,string>(); 

      foreach (XmlNode levelsItens in levelcontent) // levels itens nodes. 
      { 
       if(levelsItens.Name == "name") 
       { 
        obj.Add("name",levelsItens.InnerText); // put this in the dictionary. 
       } 


       if(levelsItens.Name == "title") 
       { 
        obj.Add("title",levelsItens.InnerText); // put this in the dictionary. 
       } 


       if(levelsItens.Name == "crystal01") 
       { 
        obj.Add("crystal01",levelsItens.InnerText); // put this in the dictionary. 

       } 

       if(levelsItens.Name == "crystal02") 
       { 
        obj.Add("crystal02",levelsItens.InnerText); // put this in the dictionary. 

       } 

       if(levelsItens.Name == "crystal02label") 
       { 
        obj.Add("crystal02label",levelsItens.InnerText); // put this in the dictionary. 

       } 


       if(levelsItens.Name == "crystal03") 
       { 
        obj.Add("crystal03",levelsItens.InnerText); // put this in the dictionary. 

       } 

      } 
      levels.Add(obj); // add whole obj dictionary in the levels[]. 
     } 
    } 


    IEnumerator LevelLoadInfo(float Wait) 
    { 
     levels[actualLevel-1].TryGetValue("name",out lvlname); 

     levels[actualLevel-1].TryGetValue("title",out lvltitle); 

     levels[actualLevel-1].TryGetValue("crystal01",out crystal01); 

     levels[actualLevel-1].TryGetValue("crystal02",out crystal02); 

     levels[actualLevel-1].TryGetValue("crystal02label",out crystal02label); 

     levels[actualLevel-1].TryGetValue("crystal03",out crystal03); 

     yield return new WaitForSeconds(Wait); 

    } 

    void Update() 
    { 
    } 

} 

모든 몇 가지 변수에 데이터를로드하기 위해이 스크립트를 사용하여 괜찮아요,하지만 정말 며칠 동안 어떤 노드에 액세스 할 수있는 기능을 만들기 위해 고군분투, 그것의 데이터를 저장하고 XML을 저장하고, 나는 다소 간단한 일이지만 그것을 이해하지 못한다 (나는 3D 아티스트, 메신저 프로그래밍 작년부터, 그래서, 아직 학습 단계에서), 예를 들어, 어떻게 내가 "crystal02"값을 편집 할 수 있을까? vel 2와 xml을 저장 하시겠습니까? 미리 감사드립니다.

+0

XML 대신 Linq를 사용하는 것이 좋습니다. – Alireza

답변

0

XML을 조금 수정해야 구문 분석 할 수 있습니다.

<crystal02>false</crystal03> 

이에 : 노드 이름이에서, 그래서 노드 이름을 닫는 일치 할 필요 열기

<crystal02>false</crystal02> 

가 하나의 요소 업데이트에 대한 귀하의 질문에 대답하기 위해, 당신이 읽을 된 XmlDocument를 사용하고 이후 문자열은 XPath로 단일 요소를 찾고 XmlDocument에서 해당 값을 업데이트 한 다음 XmlDocument를 문자열로 다시 직렬화하는 방법입니다. 업데이트 방법은 다음과 같습니다.

var doc = new System.Xml.XmlDocument(); 
// strXml is the string containing your XML from XMLData.Text 
doc.LoadXml(strXml); 
// Find the node by an XPath expression 
var l2cr3 = (XmlElement) doc.SelectSingleNode("levels/level[name='Level 2']/crystal03"); 
// Update it 
l2cr3.InnerText = "true"; 
// Update the string in memory 
var sbOut = new System.Text.StringBuilder(); 
using (var writer = XmlWriter.Create(sbOut)) { 
    doc.Save (writer); 
} 
strXml = sbOut.ToString(); 

메모리의 XML 문자열을 업데이트합니다. 그것은 파일에 지속되지 않을 것입니다. 파일을 유지하려면 doc.Load ("path/to/file.xml") 및 doc.Save ("path/to/file.xml")를 사용할 수 있습니다.

당신의 문자열이 실제로 TextAsset (Unity라고 가정)에서 나왔다는 것을 알았습니다. 그렇다면, 업데이트 된 XML 문자열을 어떻게 파일에 보존하고 싶은지, 또는 원한다면 그. 그렇다면 다른 질문이지만 Unity manual은 다음과 같이 말합니다.

런타임시 텍스트 파일 생성을위한 것이 아닙니다. 이를 위해 은 외부 파일을 읽고 쓰려면 기존 입력/출력 프로그래밍 기술을 사용해야합니다.

+0

감사! xml typo는 xml을 여기에 붙여 넣을 때 만들어졌습니다. "SelectSingleNode"는 현재 테스트 중이지만 검색 중이지만 이미 작동 중입니다. DaveC – Mauricio