2012-11-18 4 views
3

Xdocument를 사용하여 Windows 저장 응용 프로그램에서 xml을 구문 분석하려고합니다. Xdocument로 간단한 Xml 구문 분석

나는이 시도하지만, null를 반환

XDocument xDoc; 
string title= ""; 

xDoc = XDocument.Load(url); 

var elements = from x in xDoc.Descendants() 
       select new 
       { 
        title = x.Descendants("title").First().Value, 
       }; 

foreach (var el in elements) 
    _title = title; 

XML의 내용 :

<title type='text'>tiitle</title> 
<content type='text'> gfgdgdggd</content> 
<link rel='related' type='application/atom+xml' href='http....'/> 

수는 속성의 텍스트를 가져 오지 얼마나?

+0

명확히하십시오 -'title' 요소의 값이나'type' 속성의 값을 원하십니까? –

+0

귀하의 XML이 유효하지 않습니다. 단일 루트 요소가 있어야합니다. –

답변

3

, 당신의 XML이 잘못되었습니다.

<root> 
    <title type="text">title</title> 
    <content type="text">gfgdgdggd</content> 
</root> 

다음과 같은 코드로 type 속성에서 값을 검색 할 수 있습니다 : 다음과 같이

XDocument xDoc = XDocument.Parse(xml); 

var types = 
    from x in xDoc.Root.Descendants() 
    select x.Attribute("type").Value; 

내 경우 xml 선언을 :

내 코드를 테스트 할 수 있도록 그것을 조금 수정
private string xml = 
    @"<root> 
     <title type=""text"">title</title> 
     <content type=""text"">gfgdgdggd</content> 
    </root>"; 

파일 내용이 동일하면 코드를 사용하여 URL에서 XML을로드 할 수 있습니다.

+0

'루트'를 사용하여 통화가 잘됩니다. 요소에'type' 애트리뷰트가 없으면'Attribute' 메쏘드는'null'을 리턴 할 것이고'Value' 프라퍼티를 호출하게되면'.Value'를 사용하지 않고'string'으로 캐스팅하는 것을 선호합니다. 'NullReferenceException'입니다. 'string'으로 형변환하면 반환 값은 단순히 null이 될 것이고'string' 타입은이를 유지할 수 있습니다. –

+0

@ZevSpitz 예상되는 XML 구조에 따라 다르 겠지만 귀하의 접근 방식을 좋아합니다. 나는 그것이 도움이 될 것이라고 확신한다. 나는 보통 그런 경우에'! = null' 검사를 사용했다. –

+1

[방법 : 요소 값 검색 (LINQ to XML)] (http://msdn.microsoft.com/en-us/library/bb387049%28v=VS.100%29.aspx) –

0

시도 :

ZevSpitz 이미 언급 한 바와 같이
var types = 
    from e in xDoc.Descendants() 
    select (string)e.Attribute("type"); 

foreach (string type in types) { 
    Console.WriteLine(type); 
} 
+0

작동하지 않음, null 반환 – Evox

+0

모든 요소에 대해 'null'을 반환합니까? 또는 그들 중 하나만? –