问题描述
假设我们有这个简单的 xml ...
Assume we have this simple xml ...
<books>
<book>
<author/>
<title/>
</book>
<book>
<author/>
<title/>
</book>
</books>
我使用这个 xpath 来获取第一个 book 实例的元素.
I'm using this xpath to get the elements of the first book instance.
//books[1]/*
退货
<author/>
<title/>
这很好用,但我必须使用 local-name() 让它工作.我尝试了以下但这些都不起作用...
And that works fine, but I have to get it working using local-name(). I've tried the following but none of these work...
//*[local-name()='books']/*
这会返回重复的作者和标题元素,不好,我只需要第一个孩子的它们
this returns repeating author and title elements, not good, I only need them from the first child
//*[local-name()='books'][0]/*
这不会返回任何东西
基本上,我想创建一个 CSV 文件,因此输出中的第一行将是一个标题,列出书籍属性名称,后跟任意数据值.我只需要让标题部分工作.
Basically, I want to create a CSV file, so the first line in the output will be a header listing the book attribute names followed by the arbitrary data values. I only need to get the header part working.
author,title
john,The End is Near
sally,Looking for Answers
推荐答案
你说的路径表达式适合你
The path expression you say works for you
//books[1]/*
生成第一次(并且仅在这种情况下)出现的任何 <books> 的所有子节点的列表.节点.因为,在您的数据中,唯一出现的 <books>是根,同
generates a list of all child nodes of the first (and only in this case) occurrence of any <books> node. Because, in your data, the only occurrence of <books> is at the root, it is the same as
/books/*
返回两个 <book>节点,所以你说它只返回一个节点是错误的.
which returns two <book> nodes, and so you are wrong to say that it returns only one node.
很难知道您需要什么,就好像您总是将 local-name
应用于根节点,那么您就不需要知道它的名称,只需使用 即可访问它/*
,所以你只需要
It is hard to know what you need, as if you are always applying local-name
to the root node then you do not need to know its name and can access it with just /*
, so you would want simply
/*/*[1]
但是要访问 的第一个子节点节点在您要编写的文档中的任何位置
However to access the first child node of a <books> node anywhere in the document you would write
//*[local-name()='books']/*[1]
您应该尽可能地限制上下文,因为以 //
开头的 XPath 表达式将强制搜索整个文档,如果节点问题总是在根源上.
You should be careful to confine your context as much as possible, as starting the XPath expression with //
will force a search of the entire document, which is pointless and time-consuming if the node in question is always at the root.
这篇关于使用 local-name() 获取 XSLT 中的第一个子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!