Search code examples
c#xmllinq-to-xmlxelement

XElement.Element("Leve1/Level2") instead of XElement.Element("Leve1").Element("Level2")


If I have the following XML in XElement myXML variable in C#,

<Example>
   <Level1>
      <Level2>myvalue</Level2>
   </Level1>
</Example>

To get "myvalue" I need to do as below:

myXML.Element("Leve1").Element("Level2").Value;

Is there any shortcut to do it like:

myXML.Element("Leve1/Level2").Value

Thanks...


Solution

  • You can use xpath with exactly the same syntax you are after:

    var myValue = myXML.XPathSelectElement("Level1/Level2").Value;
    

    XPathSelectElement is extension method, so you need to add using System.Xml.XPath; to be able to use it.