你可以试试:
xmlstarlet sel -t -c "/root/child[position() <= 500]" file.xml
-
sel 是查询 XML 的标准方法
-
使用
sel 时始终需要-t
-
-c 用于C操作
(无论您在 xpath 中接下来选择什么)
-
/root/child 是 xpath
(显然替换为实际元素名称)
-
[position() <= 500] 选择位置(在根元素内)为 500 或更小的所有节点。
有时,我发现将路径括在括号中可以使选择起作用:
xmlstarlet sel -t -c "(/root/child)[position() <= 500]" file.xml
但一般来说,第一种方法就足够了。
所以,给定一个输入:
<root>
<child>...</child>
<child>...</child>
...
</root>
你会得到:
<child>...</child><child>...</child>...
请注意,没有语法上有效的 XML。
要使用换行符分隔,请尝试以下变体:
xmlstarlet sel -t -m "/root/child[position() <= 500]" -c "." -n file.xml
-
-m刚刚米连接 xpath
(不产生输出)
-
-c "." 复制匹配的节点
-
-n 附加一个n每个匹配/复制节点后的换行符
第 2 部分 - 选择某种类型的前“n”个节点
假设您想从以下 XML('example.xml')中获取前 3 个苹果:
<root>
<apple>Braeburn</apple>
<banana>Chiquita</banana>
<apple>Granny Smith</apple>
<plantain/>
<apple>Cox</apple>
<apple>Elstar</apple>
<apple/>
<apple/>
</root>
然后你可以使用:
xmlstarlet sel -t -m "/root/apple[position() <= 3]" -c "." -n example.xml
这又与前面的例子基本相同。
通过添加元素名称 ('apple'),您将专门选择前三个苹果节点,如以下输出所示:
<apple>Braeburn</apple>
<apple>Granny Smith</apple>
<apple>Cox</apple>
注意<banana>Chiquita</banana> 和<plantain/> 是如何被忽略的。
它们不是<apple/> 类型的直接<root/> 子代。
奖金:
假设您想获得第三个苹果,那么您可以使用:
xmlstarlet sel -t -c "/root/apple[position() = 3]" example.xml
这会给你:<apple>Cox</apple>。
甚至更短:
xmlstarlet sel -t -c "/root/apple[3]" example.xml
再次给你同样的结果。