How to use XPath with XElement or LINQ ?

How to use XPath with XElement or LINQ ?

Asked on January 8, 2019 in XML.
Add Comment


  • 9 Answer(s)

         To use XPath with LINQ to XML add by using declaration for System.Xml.XPath which will bring the extension methods of System.Xml.XPath.Extensions into scope.

    Some instance,

    var value = (string)xml.XPathEvaluate("/response/data/hash");
    
    Answered on January 8, 2019.
    Add Comment

         To use xpath with xelement or linq, allow XPathSelectElement, XPathSelectElements and XPathEvaluate to classify XPath expressions across an XNode they are all extension methods on XNode. Also use CreateNavigator to create an XPathNavigator for an XNode.

     

    Answered on January 8, 2019.
    Add Comment

         The descendants will find every element from all the XML and lists all the objects that matches the name that are detailed. So, in our case hash is the name which it founds.

    Better do it,

    var hash = xml.Descendants("hash").FirstOrDefault().Value;
    

         The break by alone like,

    var elements = xml.Descendants("hash");
    var hash = elements.FirstOrDefault();
     
    if(hash != null)
      hash.Value // as hash can be null when default.
    

         By this way we may get attributes, nodes elements also.

    Answered on January 8, 2019.
    Add Comment
    <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>
    Answered on February 28, 2019.
    Add Comment
    var elements = xml.Descendants("hash");
    var hash = elements.FirstOrDefault();
    
    if(hash != null)
     hash.Value // as hash can be null when default.
    Answered on February 28, 2019.
    Add Comment
    XElement xml = XElement.Parse(@"...your xml...");
    XElement hash = xml.Element("data").Element("hash");
    Answered on February 28, 2019.
    Add Comment
    var xpath = CreateXpath.Where(e => e.TargetElementName == "td" && e.Parent.Name == "tr");
    
    var xpath = CreateXpath.Where(e => e.TargetElementName == "td").Select(e => e.Text);
    Answered on February 28, 2019.
    Add Comment

    XElement root = new XElement(“Root”, new XElement(“Child1”, 1), new XElement(“Child1”, 2), new XElement(“Child1”, 3), new XElement(“Child2”, 4), new XElement(“Child2”, 5), new XElement(“Child2”, 6) );

    Answered on February 28, 2019.
    Add Comment

    Composition of a LINQ to XML query is somewhat parallel to composition of an XPath expression, although very different in syntax.

    Answered on February 28, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.