2016-10-13 5 views
1

여기에 XML의 스 니펫이 나와 있습니다 (실제로는 수천 개에 불과하지만 실제로는 수천 가지가 있습니다). 내가해야 할 일은C# Linq을 사용하여 XML을 쿼리하여 일치 항목을 찾습니다.

<?xml version="1.0" encoding="UTF-8"?> 
<information_code version="3.5"> 
    <entry code="000" title="Function, data for plans and description"/> 
    <entry code="001" title="Title page"/> 
    <entry code="002" title="List of pages or data modules"/> 
    <entry code="003" title="Change records and highlights"/> 
    <entry code="004" title="Access illustration"/> 
</information_code> 

다음 '제목'속성의 값을 반환의 '코드'내 쿼리에 전달할 값을 가진 속성과 일치합니다. 정말 어렵지는 않겠지 만 서클에서 돌아 다니고 있습니다.

내가 현재있는 곳이지만 일치하지 않으면 항상 잡히게됩니다. 분명히 내 쿼리에 문제가 있습니다.

private string getInfoName(string infoCode) 
{ 
    XDocument mydoc = XDocument.Load(GlobalVars.pathToInfoCodes); 
    string name = string.Empty; 

    try 
    { 
     var entry = mydoc 
      .Elements("entry") 
      .Where(e => e.Attribute("code").Value == infoCode) 
      .Single(); 

     name = entry.Attribute("title").Value; 
    } 
    catch 
    { 
     MessageBox.Show("Info code not recognised: " + infoCode); 
    }   
    return name; 
} 

답변

1

문제는 당신이 Elements를 사용하는 경우에만이 시점에서 <information_code> 당신이 현재에있는 수준에서 검색하는 것입니다 - 그래서 거기에 더 <entry> 요소가 없습니다.

당신은 .Element("information_code").Elements("entry")를 사용하거나 대신 .Descendants 사용할 수 있습니다

string wantedCode = "001"; 

var title = XDocument.Load(GlobalVars.pathToInfoCodes) 
     .Descendants("entry") 
     .Where(e => e.Attribute("code")?.Value == wantedCode) 
     .Select(e => e.Attribute("title").Value).FirstOrDefault(); 

당신은 쿼리 구문 함께 할 수도 있습니다. ?. 구문은 C# 6.0 널 전파 것을

var title = (from e in XDocument.Load("data.xml").Descendants("entry") 
      where e.Attribute("code")?.Value == wantedCode 
      select e.Attribute("title")?.Value).FirstOrDefault(); 

참고 : 친절을 보일 수 있습니다. 이전 버전의 C#을 사용하고 있다면 변수에 속성을 저장하고 그 값이 null이고 그 다음에 만 액세스가 .Value

+0

이되어야합니다. 정말 감사합니다. –

+0

@ Can'tCodeWon'tCode - 당신은 환영합니다 :) –

+0

항상 'Value' 속성을 사용하여 캐스팅하는 것이 좋습니다. –

관련 문제