문제

그래서 XML 파일을 구문 분석하려고합니다.

 <?xml version="1.0" encoding="utf-8" ?>
<Root>    
  <att1 name="bob" age="unspecified" xmlns="http://foo.co.uk/nan">    
  </att1>    
</Root>

다음 코드 사용 :

XElement xDoc= XElement.Load(filename);
var query = from c in xDoc.Descendants("att1").Attributes() select c;
foreach (XAttribute a in query)
{
    Console.WriteLine("{0}, {1}",a.Name,a.Value);
}

XML 파일에서 xmlns = "http://foo.co.uk/nan"을 삭제하지 않는 한 콘솔에 아무것도 기록되지 않습니다. 그 후에는 예상대로 속성 이름과 값 목록을 얻습니다. !

편집 : 서식.

도움이 되었습니까?

해결책

코드에서 동일한 네임 스페이스를 사용해야합니다.

XElement xDoc= XElement.Load(filename);
XNamespace ns = "http://foo.co.uk/nan";
var query = from c in xDoc.Descendants(ns + "att1").Attributes() select c;
foreach (XAttribute a in query)
{
    Console.WriteLine("{0}, {1}",a.Name,a.Value);
}

속성은 기본값을 선택하지 않습니다 (xmlns=....) 네임 스페이스, 따라서 자격을 갖추지 않아도됩니다. 네임 스페이스 태그 (xmln:tags=....)은 순전히 문서 또는 API 사용에 국한되며 이름은 항상 네임 스페이스 + 로컬 이름이므로 항상 네임 스페이스를 지정해야합니다.

다른 팁

당신의 전화 자손 네임 스페이스가없는 "att1"이라는 요소에 대한 쿼리입니다.

당신이 전화했다면 Descendants("{http://foo.co.uk/nan}att1") 네임 스펙트 한 요소를 선택하지만 Non-Namespaced 요소는 선택하지 않습니다.

다음과 같은 네임 스페이스에서 "att1"이라는 요소를 선택할 수 있습니다.

var query = from c in xDoc.Descendants() where c.Name.LocalName == "att1" select c.Attributes;

네임 스페이스를 지정해야합니다 Descendants 다음과 같이 전화하십시오.

XNamespace ns = "http://foo.co.uk/nan";
foreach (XAttribute a in xDoc.Descendants(ns + "att1"))
{
    Console.WriteLine("{0}, {1}",a.Name,a.Value);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top