2013-06-30 2 views
1

.xml 파일을 읽는 데 거의 성공하지 않고 지난 몇 시간 동안 노력해 왔습니다. C#에서 .XML 파일 읽기

내가 시도 :

XmlReader reader = XmlReader.Create("ChampionList.xml"); 

     reader.ReadToFollowing("Name"); 
     reader.MoveToFirstAttribute(); 
     string nume = reader.Value; 
     MessageBox.Show(nume); 

내 XML은 다음과 같습니다

<?xml version="1.0" encoding="utf-8" ?> 
<main> 
    <Champion> 
    <Name>Aatrox</Name> 
    <Counter>Soraka</Counter> 
    </Champion> 
    <Champion>  
    <Name>Ahri</Name> 
    <Counter>Diana</Counter>  
    </Champion> 
</main> 

내가 버튼을 누를 때마다 이름과 카운터를 읽고 싶습니다. 때마다 새로운 하나 (첫 번째 버튼을 누르십시오 - 첫 번째 챔피언 등등).

나를 도와 줄 사람이 있습니까? 또한, 코드의 설명 비트가 좋을 것입니다, 많은 루프와 물건이 있다면, 나는 여전히 많이 배울 필요가있다.

+0

코드를 편집 해 주셔서 감사합니다. – Xzenon

+0

XmlReader를 사용해야하는 이유는 무엇입니까? LINQ to XML (XDocument)을 사용해보십시오. –

답변

1

당신에게의 내용을 얻기 위해 XmlReader보다 높은 수준의 인터페이스로 작업하는 것이 더 쉬울 수도 있습니다. 예를 들어, 다음과 같이 XML Linq에이 작업을 수행 할 수 :

// read in the entire document 
var document = XDocument.Load("ChampionsList.xml"); 

// parse out the relevant information 
// start with all "Champion" nodes 
var champs = documents.Descendants("Champion") 
    // for each one, select name as the value of the child element Name node 
    // and counter as the value of the child element Counter node 
    .Select(e => new { name = e.Element("Name").Value, counter = e.Element("Counter").Value }); 

// now champs is a list of C# objects with properties name and value 

foreach (var champ in champs) { 
    // do something with champ (e. g. MessageBox.Show) 
} 
+0

''Descendants ("Name"). 요소 ("Name")'에, 그리고 나는''Counter ''에''up-vote ''할 것이다. –

+0

@ChuckSavage 잘 부탁드립니다. 나는 변화를 만들었습니다 – ChaseMedallion

+0

고마워요, 그것은 효과적이었습니다 :) Descendants()와 Single()과 Element()의 차이점은 무엇입니까? – Xzenon

1

XML 유효성을 테스트하기 위해 파일 확장명을 .XML로 설정 한 다음 Internet Explorer 창에 놓는 것이 매우 쉽다는 것을 발견했습니다. Internet Explorer에는 아주 좋은 XML 뷰어가 내장되어있어 오류가 있는지 알려줍니다.

(편집 :되게 XML이 유효하지 않은 것에 대해 제거 특정 제안 -이 마크 업 문제로 인해 발생 된 것으로 나타납니다.)

+0

클레임에 대해 확신합니까? – rene

+0

내가 대답 할 때 XML이 다르게 보였다. 이 대답은 현재 Internet Explorer에서 유효성을 검사하는 팁 이외에는 유용하지 않습니다. – StilesCrisis

+0

나는 단지 루트 태그가 나타나는지 확인했다 ... 나는 어떤 태그도 추가하거나 제거하지 않았다 ... 당신의 대답은 내가 질문 편집을 시작하게했다 ... – rene

1

사용 ReadElementContentAsString를 요소

XmlReader reader = XmlReader.Create("ChampionList.xml"); 

reader.ReadToFollowing("Name"); // read until element named Name 
string nume = reader.ReadElementContentAsString(); // read its content 
MessageBox.Show(nume); 
0

왜 한 번 목록에 읽지 않는 토록 버튼을 누를 때 당신의 목록에서 꺼내. XmlTextReader reader = 새 XmlTextReader ("yourfile.xml");

  string elementName = ""; 

      List<string[]> Champion = new List<string[]>(); 
      string name = "";    

      while (reader.Read()) // go throw the xml file 
      { 

       if (reader.NodeType == XmlNodeType.Element) //get element from xml file 
       { 

        elementName = reader.Name; 
       } 
       else 
       { 

        if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue)) //fet the value of element 
        { 
         switch (elementName) // switch on element name weather Name or Counter 
         { 
          case "Name": 
           name = reader.Value; 
           break; 
          case "Counter": 
           string[] value = new string[] { name, reader.Value }; //store result to list of array of string 
           Champion.Add(value); 
           break; 

         } 
        } 
       } 
      }