Select last XML node

c#, xml

Solution

Using LINQ to XML

var value = XDocument.Load("path")
                      .Descendants("Product")
                      .Last()
                      .Attribute("Name").Value;

Also you can use `XPath` with `LINQ to XML`

var value = XDocument.Load("path")
             .XPathSelectElement("//LastProductInformation/Product[last()]")
             .Attribute("Name").Value;

Note: Make sure you have a reference to `System.Xml.Linq` namespace from your project.

Problem

I have this XML code: ``` <AriaGostarInformation> <MenuInformation> <MenuNames Name="0" href="default.aspx">home</MenuNames> <SubMenuNames parentName="1"> fgfgfgfgs </SubMenuNames> <SubMenuNames parentName="3"> </SubMenuNames> </MenuInformation> <SliderInformation> <SliderImageAddress>..\..\Img\Hydrangeas.jpg,</SliderImageAddress> <SliderImageAddress>..\..\Img\Jellyfish.jpg,</SliderImageAddress> <SliderImageAddress>..\..\Img\Koala.jpg,</SliderImageAddress> <SliderImageAddress>..\..\Img\Lighthouse.jpg,</SliderImageAddress> <SliderImageAddress>..\..\Img\Penguins.jpg,</SliderImageAddress> <SliderImageAddress>..\..\Img\Tulips.jpg,</SliderImageAddress> </SliderInformation> <LastProductInformation> <Product Name="147"> <Subject> </Subject> <ProductImageAddress>http://localhost:1209/ckeditor/plugins/imagebrowser/browser/Hydrangeas.jpg</ProductImageAddress> <ProductDes> &lt;p&gt;&lt;span style="color:#FFA07A;"&gt;qwqweqweqe&lt;/span&gt;qwe&lt;/p&gt; &lt;p&gt;&lt;span style="font-size:11px;"&gt;qweqweqw&lt;/span&gt;e&lt;/p&gt; </ProductDes> </Product> <Product Name="dsa"> <Subject>salm</Subject> <ProductImageAddress>http://localhost:1209/ckeditor/plugins/imagebrowser/browser/Hydrangeas.jpg</ProductImageAddress> <ProductDes> &lt;p&gt;sdADASDASDASDASDASDASD&lt;/p&gt; &lt;p&gt;ASDASDASDADASDASDASDASDA&lt;/p&gt; &lt;p&gt;ASDASDASDASDASDASDASDASDASD&lt;/p&gt; </ProductDes> </Product> </LastProductInformation> </AriaGostarInformation> ``` I want select last `product` node in `LastProductInformation` and get this node's attribute. My code is: ``` XmlDocument xdoc = new XmlDocument(); xdoc.Load(AppDomain.CurrentDomain.BaseDirectory + @"\static\css\xml\data.xml"); XmlNode xparent = xdoc.SelectSingleNode("//LastProductInformation"); var b = xparent.SelectSingleNode("/Product[last()]").Attributes["Name"].Value; ``` but this returns null. What should I do?

Original source