请教一个XPath的写法

number321 2012-03-10 10:20:10
请问怎样在XML文档中,找到最后一个以p开头的XML元素呢

//*[starts-with(name(),'p')] ,这是找到以p开头的XML元素,那么"最后一个"应该用什么方法来表示呢,last()吗,last好像是没有参数的,应该放在哪边呢?
...全文
70 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
number321 2012-03-12
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 fangxinggood 的回复:]

var nodes = xmlDoc.SelectNodes("(//*[starts-with(name(),'p')])[last()]");
[/Quote]

这个是有效的,谢谢了
机器人 2012-03-10
  • 打赏
  • 举报
回复
在最后加 [last()]

//*[starts-with(name(),'p')][last()]
number321 2012-03-10
  • 打赏
  • 举报
回复
现在我已经在谓语,也就是[]中写了内容了,那么last应该怎么写呢
bdmh 2012-03-10
  • 打赏
  • 举报
回复
摘自msdn

last() 函数对集合中的最后一个元素返回 True。 注意,last 相对于父节点。

示例
表达式 引用
book[last()]
最后一个 <book> 元素。

book/author[last()]
每个 <book> 元素内的最后一个 <author> 元素。

(book/author)[last()]
<book> 元素内整个 <author> 元素集中的最后一个 <author> 元素。

机器人 2012-03-10
  • 打赏
  • 举报
回复
var nodes = xmlDoc.SelectNodes("(//*[starts-with(name(),'p')])[last()]");
number321 2012-03-10
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 fangxinggood 的回复:]

在最后加 [last()]

//*[starts-with(name(),'p')][last()]
[/Quote]

这个好像也没用


<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<!-- XmlComment -->
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="TEST">
<title lang="en">H P</title>
<author>J K. R</author>
<year>2012</year>
<price>00.00</price>
</book>
</bookstore>


这样一个XML文件,如果我这样写的话

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"D:\test.xml");
XmlNode xNode = xmlDoc.SelectSingleNode("//*[starts-with(name(),'p')][last()]");
if (xNode == null)
{
MessageBox.Show("null");
}
else
{
MessageBox.Show(xNode.InnerXml);
}


得到的是第一个值30.00.
正常情况下只有price是以p开头的,应该是得到最后一个00才对的吧.

110,545

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧