XElement 또는 LINQ에서 XPath를 사용하는 방법은 무엇입니까?
다음 XML을 고려하십시오.
<response>
<status_code>200</status_code>
<status_txt>OK</status_txt>
<data>
<url>http://bit.ly/b47LVi</url>
<hash>b47LVi</hash>
<global_hash>9EJa3m</global_hash>
<long_url>http://www.tumblr.com/docs/en/api#api_write</long_url>
<new_hash>0</new_hash>
</data>
</response>
<hash>요소 의 값을 얻을 수있는 아주 짧은 방법을 찾고 있습니다. 나는 시도했다 :
var hash = xml.Element("hash").Value;
그러나 그것은 작동하지 않습니다. 에 XPath 쿼리를 제공 할 수 XElement있습니까? 이전 System.Xml프레임 워크로 다음과 같이 할 수 있습니다.
xml.Node("/response/data/hash").Value
LINQ 네임 스페이스에 이와 같은 것이 있습니까?
최신 정보:
이것으로 좀 더 돌아 다니면서 내가하려는 일을 할 수있는 방법을 찾았습니다.
var hash = xml.Descendants("hash").FirstOrDefault().Value;
누구에게 더 나은 해결책이 있는지 궁금합니다.
LINQ to XML에서 XPath를 사용하려면에 대한 using 선언을 추가하면 System.Xml.XPath의 확장 메서드가 System.Xml.XPath.Extensions범위에 포함됩니다.
귀하의 예에서 :
var value = (string)xml.XPathEvaluate("/response/data/hash");
다른 사람들은 "네이티브"LINQ to XML 쿼리를 사용하여 원하는 작업을 수행하는 방법을 완전히 합리적으로 제안했습니다.
그러나, 대안을 많이 제공하는 이익을 고려 XPathSelectElement, XPathSelectElements및 XPathEvaluate에 대한 XPath 식을 평가하기 위해 XNode(그들은 모든 확장 방법이야 XNode). 당신은 또한 사용할 수 있습니다 CreateNavigator만들 XPathNavigator를 들어 XNode.
개인적으로 저는 LINQ 팬이기 때문에 LINQ to XML API를 직접 사용하는 것을 좋아하지만 XPath에 더 익숙하다면 위의 내용이 도움이 될 것입니다.
LINQ to XML을 다룰 때 LINQ를 사용하여 실제 개체를 가져 오지 않는 이유를 참조하십시오.
하위 항목은 전체 XML에서 각 요소를 찾고 지정된 이름과 일치하는 모든 개체를 나열합니다. 따라서 귀하의 경우 해시는 찾은 이름입니다.
그래서하기보다는
var hash = xml.Descendants("hash").FirstOrDefault().Value;
나는 다음과 같이 헤어질 것입니다.
var elements = xml.Descendants("hash");
var hash = elements.FirstOrDefault();
if(hash != null)
hash.Value // as hash can be null when default.
이런 식으로 속성, 노드 요소 등을 얻을 수도 있습니다.
Check this article to get clear idea about it so that it helps. http://www.codeproject.com/KB/linq/LINQtoXML.aspx I hope this will help you.
You can use .Element() method to chain the elements to form XPath-like structure.
For your example:
XElement xml = XElement.Parse(@"...your xml...");
XElement hash = xml.Element("data").Element("hash");
I have tried to come up with a LINQesq framework for generating xpath. It lets you describe xpath using c# lambda expressions
var xpath = CreateXpath.Where(e => e.TargetElementName == "td" && e.Parent.Name == "tr");
var xpath = CreateXpath.Where(e => e.TargetElementName == "td").Select(e => e.Text);
Not sure if this is helpful in this context, but you can find documentation here:
http://www.syntaxsuccess.com/viewarticle/how-to-create-xpath-using-linq
참고URL : https://stackoverflow.com/questions/3642829/how-to-use-xpath-with-xelement-or-linq
'program story' 카테고리의 다른 글
| Python + Selenium WebDriver를 사용하여 쿠키를 저장하고로드하는 방법 (0) | 2020.10.18 |
|---|---|
| Emacs 버퍼에서 단어의 모든 발생을 강조하는 방법은 무엇입니까? (0) | 2020.10.18 |
| Amazon S3 : 정적 웹 사이트 : 사용자 지정 도메인 또는 하위 도메인 (0) | 2020.10.18 |
| Angular2는 본문 태그에 클래스 추가 (0) | 2020.10.18 |
| JSON을 CSV로 변환하는 동안 JSON 키의 순서 유지 (0) | 2020.10.18 |