选择最后一个XML节点

3

我有这段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>   

我想选择LastProductInformation中的最后一个product节点并获取该节点的属性。 我的代码如下:

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;

但是这将返回空值。我应该怎么办?
2个回答

7
使用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 命名空间。


我使用了你的代码,但是出现了以下错误: 对象引用未设置为对象的实例。 - undefined
@user3243749,你能否更新你目前正在使用的代码到你的问题中?我已经尝试过这段代码和你的XML文档,它们都可以正常工作。 - undefined
var value = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + @"\static\css\xml\data.xml").XPathSelectElement("//LastProductInformation/Product[last()]").Attribute("Name").Value; - undefined
代码没有问题。确保你的路径是正确的。 - undefined
@user3243749你尝试过第一个解决方案了吗? - undefined

0
你不需要改用linq。
var b = xparent.SelectSingleNode("//Product")[last()].Attributes["Name"].Value;
< p > last() 的作用类似于索引,因此应该放在最后。 < /p >

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接