使用 xmlstarlet 提取和转储元素 [英] Extracting and dumping elements using xmlstarlet

查看:27
本文介绍了使用 xmlstarlet 提取和转储元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用 xmlstarlet 从我的 xml 中提取和打印元素的方法;例如,如果我的 xml 是

<书店><书><title lang="eng">哈利波特</title><价格>29.99</价格><书><title lang="eng">学习 XML</title><价格>39.95</价格></书店>

我想将 price = 29.99 的 book 元素打印为:

<title lang="eng">哈利波特</title><价格>29.99</价格>

我理解 xpath 查询选择这样一个元素 (/bookstore/book[price=29.99]) 但是我无法在标准输出上打印/转储它.如果我使用 '-v' 选项并使用 -v (.) 我不会得到我想要的输出(其中包含所有标签),我只会得到文本值.应该有一种方法可以按原样简单地转储所选元素,这就是我正在寻找的.

感谢期待.

解决方案

使用-c"(复制)选项,应该可以实现您的目标:

xmlstarlet sel -t -c "/bookstore/book[price=29.99]" books.xml<书><title lang="eng">哈利波特</title><价格>29.99</价格>

您可以通过在sel"之后添加全局-C"开关来观察xmlstarlet内部生成的XSLT.这显示了复制选项如何生成 xslt 复制结构:

<预><代码>...<xsl:template name="t1"><xsl:copy-of select="/bookstore/book[price=29.99]"/></xsl:模板>...

这会导致包含命名空间节点、子节点和属性节点,参见.XSLT 规范 (参见 w3schools 摘要).

I am looking for a way to extract and print an element from my xml using xmlstarlet; for example if my xml is

<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>

<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>

</bookstore>

I would like to print out book element with price = 29.99 as:

<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>

I understand the xpath query to select such an element (/bookstore/book[price=29.99]) but I am not able to print/dump it on stdout. If I use the '-v' option and use -v (.) I don't get the output as I want (with all the tags in it) I just get the text values. There ought to be a way to simply dump selected element as it is, and that's what I am looking for.

Thanks in anticipation.

解决方案

Using the "-c" (copy) option, should achieve what you're after:

xmlstarlet sel -t -c "/bookstore/book[price=29.99]" books.xml

<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>

You can watch the XSLT generated internally in xmlstarlet by adding the global "-C" switch after "sel". This shows how the copy option results in an xslt copy-of construct:

...
<xsl:template name="t1">
  <xsl:copy-of select="/bookstore/book[price=29.99]"/>
</xsl:template>
...

This results in namespace nodes, child nodes, and attributes nodes being included, cf. the XSLT spec (see w3schools summary).

这篇关于使用 xmlstarlet 提取和转储元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆