选择最后一个XML节点

时间:2014-02-04 09:31:38

标签: c# xml

我有这个XML代码:

<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>   

我想在product中选择最后一个LastProductInformation节点并获取此节点的属性。 我的代码是:

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;

但是返回null。我该怎么办?

2 个答案:

答案 0 :(得分:5)

使用LINQ to XML

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

您也可以将XPathLINQ to XML

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

注意:确保您的项目中有System.Xml.Linq命名空间的引用。

答案 1 :(得分:0)

您无需更改为linq。

var b = xparent.SelectSingleNode("//Product")[last()].Attributes["Name"].Value;

last()就像一个索引,所以应该在最后。