2013-06-06 2 views
0

Linq를 사용하여 ID 정보를 얻는 방법은 무엇입니까? 그것들을 int 배열에 추가하려고합니다.LINQ to XML 요소를 가져 오겠습니까?

<FactionAttributes> 
    <name>Player</name> 
    <id>0</id> 
    <relationModifier>1</relationModifier> 
    <relations> 
     <id0>100</id0> 
     <id1>50</id1> 
     <id2>50</id2> 
     <id3>50</id3> 
     <id4>50</id4> 
     <id5>50</id5> 
    </relations> 
    </FactionAttributes> 

그건 내 XML입니다.

여기까지 제가 사용하고있는 코드입니다.

void InitFactions() 
     { 
      int count = 0; 
      string filepath = Application.dataPath + "/Resources/factiondata.xml"; 
      XDocument factionXML = XDocument.Load(filepath); 

      var factionNames = from factionName in factionXML.Root.Elements("FactionAttributes") 
       select new { 
        factionName_XML = (string)factionName.Element("name"), 
        factionID_XML = (int)factionName.Element("id"), 
        factionRelations_XML = factionName.Element("relations")// Need to turn this into array. 
      }; 

      foreach (var factionName in factionNames) 
       ++count; 

      foreach (var factionName in factionNames) 
      { 
       Factions f = new Factions();    
       f.otherFactionsName = new string[count]; 
       f.otherFactionsRelation = new int[count]; 
       int others = 0; 

       f.FactionName = factionName.factionName_XML; 

       Debug.Log(factionName.factionRelations_XML); 

       // Adds Rivals, not self to other list. 
       foreach (var factionName2 in factionNames) 
       { 
        if (factionName.factionID_XML == factionName2.factionID_XML) 
         continue; 
        f.otherFactionsName[(int)factionName2.factionID_XML] = factionName2.factionName_XML; 

// THIS IS WHERE IM ADDING THE RELATIONS IN // 
        f.otherFactionsRelation[(int)factionName2.factionID_XML] = factionName.factionRelations_XML[(int)factionName2.factionID_XML]; 
        Debug.Log(f.FactionName + " adds: " + factionName2.factionName_XML); 
        ++others; 
       } 
      } 
     } 

노드를 사용하여 여러 번 시도했지만 그 중 무엇을 사용하지 않았습니다. 올바른 구문을 파악할 수없는 것 같습니다.

+1

Wh 예상 출력은? 01005050505050? – James

+0

배열을 100 50 50 50 50 50으로 채우기 만하면됩니다. –

+0

쿼리에 만족하면 가장 좋은 솔루션 옆의 체크를 클릭하여 대답을 수락해야합니다. – James

답변

0
XDocument doc = XDocument.Load(Path); 

//To get <id> 
var MyIds = doc.Element("FactionAttributes").Element("id").Value; 

//To get <id0>, <id1>, etc. 
var result = doc.Element("FactionAttributes") 
       .Element("relations") 
       .Elements() 
       .Where(E => E.Name.ToString().Contains("id")) 
       .Select(E => new { IdName = E.Name, Value = E.Value}); 

당신이 당신이 아이디하려는 경우 관계 ID가이 간단한 쿼리

var doc = XDocument.Load("c:\\tmp\\test.xml"); 
var ids = doc.Descendants("relations").Elements().Select(x => x.Value); 

를 사용 직후 경우의 int의 배열이

.Select(E => Convert.ToInt32(E.Value)).ToArray(); 
+0

그리고 고맙습니다. 두 좋은 예. –

0

과 선택을 교체하려는 경우와 1 배열의 관계 ID가 이것을 사용한다

var id = doc.Descendants("id").Select(x=>x.Value).Concat(doc.Descendants("relations").Elements().Select(x => x.Value)); 
+0

생각해 주셔서 감사합니다. 감사합니다. –