2012-06-16 2 views
0

XML 파일에서 데이터를 읽고 텍스트 상자에 표시하려고하지만 마지막 요소/특성 (이 경우 "내구성") 만 표시하려고합니다. 여기 내 XML 파일이C# XmlTextReader가 모든 요소 및 특성을 읽지 못함

<?xml version="1.0" encoding="utf-8"?> 
<Character> 
    <Name 
    Name="Test" /> 
    <Age 
    Age="19" /> 
    <Class 
    Class="Necromancer" /> 
    <Strength 
    Strength="1" /> 
    <Dexterity 
    Dexterity="2" /> 
    <Intelligence 
    Intelligence="3" /> 
    <Speed 
    Speed="4" /> 
    <Endurance 
    Endurance="5" /> 
</Character> 

내가 데이터를 표시하는 버튼을 클릭 할 때마다 그래서

XmlTextReader reader = new XmlTextReader(openFileDialog1.FileName); 
while (reader.Read()) 
{ 
    if (reader.HasAttributes) 
    { 
    for (int i = 0; i < reader.AttributeCount; i++) 
    { 
     reader.MoveToAttribute(i); 
     switch (reader.Name) 
     { 
     case "Name": 
      DisplayBox.Text = "Name: " + reader.Value + "\n"; 
      break; 
     case "Age": 
      DisplayBox.Text = "Age: " + reader.Value + "\n"; 
      break; 
     case "Class": 
      DisplayBox.Text = "Class: " + reader.Value + "\n"; 
      break; 
     case "Strength": 
      DisplayBox.Text = "Strength: " + reader.Value + "\n"; 
      break; 
     case "Dexterity": 
      DisplayBox.Text = "Dexterity: " + reader.Value + "\n"; 
      break; 
     case "Intelligence": 
      DisplayBox.Text = "Intelligence: " + reader.Value + "\n"; 
      break; 
     case "Speed": 
      DisplayBox.Text = "Speed: " + reader.Value + "\n"; 
      break; 
     case "Endurance": 
      DisplayBox.Text = "Endurance: " + reader.Value + "\n"; 
      break; 
     default: 
      break; 
     } 
    } 
     reader.MoveToElement(); 
    } 
} 

다음과 같이 독자에 대한 나의 코드는 텍스트 상자에 표시 유일한 것은 인내입니다 : 5

답변

1

보인다. 따라서 다음을 사용할 수 있습니다 :

string[] supportedAttributes = new []{"Name", "Age", "Class", "Strength", "Dexterity", "Intelligence", "Speed", "Endurance"}; 
while (reader.Read()) 
{ 
    if (reader.HasAttributes) 
    { 
    for (int i = 0; i < reader.AttributeCount; i++) 
    { 
     reader.MoveToAttribute(i); 
     if(supportedAttributes.Any(a=>a == reader.Name)) 
      DisplayBox.Text += string.Format("{0}: {1} \n", reader.Name, reader.Value); 
    } 
    reader.MoveToElement(); 
    } 
} 
+0

정말 고맙습니다. –

0

대신

DisplayBox.Text = 

당신은

처럼 사용한다
DisplayBox.Text += 

필수 항목입니다. 당신이 스위치 조건 또한

DisplayBox.Text += 

모두와 함께

DisplayBox.Text = 

를 교체해야 할 매우 유사 같은

0

현재 모든 노드를 루핑하고 있습니다.

마지막으로 루프가 마지막 노드에서 중지됩니다. 엔듀 런스 노드뿐입니다.

그러면 내구성으로 결과가 표시됩니다.

특정 조건을 확인하고 만족하면 루프 밖으로 나와야합니다.

또는

당신이 다음 @Kostya@Furqan 답변에 따라 텍스트 상자의 모든 값을 표시하려면

.

1

직접 질문에 답변하지 않고 대신 코드를 작성하는 대체 방법을 제공합니다.

특히 switch 문이 반복되어 반복을 제거 할 수 있습니다.

또한 switch 문을 사용하면 코드를 특정 값으로 고정시킬 수 있습니다. 사용하려는 속성 이름 목록을 동적으로 변경할 수 없습니다 (예 : 다른 언어의 경우). 지금은없는 유일한 것은이 map 기능에 대한 정의입니다

var xd = XDocument.Load(openFileDialog1.FileName); 

var query = 
    from xe in xd.Descendants() 
    from xa in xe.Attributes() 
    let r = map(xa.Name.ToString(), xa.Value) 
    where r != null 
    select r; 

DisplayBox.Text = String.Join("", query); 

:

여기 내 코드입니다. 이것은 코드가 약간 초초 해지는 곳입니다.이름과

첫 시작은 당신이 찾고있는 :

var names = new [] 
{ 
    "Name", "Age", "Class", 
    "Strength", "Dexterity", "Intelligence", 
    "Speed", "Endurance", 
}; 

지금 우리가 매핑에 대한 책임 변수의 몇 가지 정의 할 필요가 :

var nameMap = 
    names 
     .ToDictionary(
      n => n, 
      n => (Func<string, string>) 
       (t => String.Format("{0}: {1}\n", n, t))); 

Func<string, string, string> map = 
    (n, v) => 
     nameMap.ContainsKey(n) ? nameMap[n](v) : null; 

그것은 조금 까다로운을, 하지만 데이터를 얻기 위해 이름 목록을 최종 쿼리와 잘 분리하고 유지해야하는 부분에 대해 코드를보다 명확하게 유지할 것입니다.

관련 문제