【问题标题】:How to extract properties from a xml file matching pattern on keys如何从键上匹配模式的 xml 文件中提取属性
【发布时间】:2017-04-24 09:48:33
【问题描述】:

我有一个类似这样的文件

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
<property><name>key1.somestuff.someotherstuff</name><value>value1</value></property><property><name>key2.somestuff.someotherstuff</name><value>value2</value></property></configuration>

所以我作为输入获得的文件格式不正确,我需要将其中一些与模式匹配的属性复制到另一个 xml 文件。 我如何在 shell 中为这个文件提取段(使用 grep 或 sed 或任何此类工具),以获取键中的给定模式。 例如,如果代码格式正确,我可以使用:

grep --no-group-separator -a2 "key1"

如何为某个键(如 key1)提取段:

<property>
  <name>key1.somestuff.someotherstuff</name>
  <value>value1</value>
</property>

【问题讨论】:

  • 您的 xml 输入不是有效的 xml。
  • @Cyrus 是的,抱歉,这是手写示例,已更正。
  • 好的。您的示例包含两次key1.somestuff.someotherstuff。这是故意的吗?
  • @Cyrus 只是为了给出格式,将名称更改为不同的值以具有不同的值。不,那不是故意的
  • @user1560339:你能用xmllint吗?可以下载安装吗?

标签: xml bash shell sed


【解决方案1】:

grepxml 一起使用通常不是一个好主意。对于这种情况,建议使用xmllint 等可识别 XML 的工具。链接中提供了下载和安装说明。

使用xmllint 一个简单的xpath 解析器逻辑,如下所示

xmllint --xpath '/configuration/property[contains(name,"key1.somestuff.someotherstuff")]' input-xml

应该可以解决您的问题。逻辑很简单。从根节点configurationproperty 开始,并获取节点name 的值,前提是它包含您需要的字符串。

由于您在描述中的文件格式为扁平线,因此上述命令会生成如下扁平输出:

xmllint --xpath '/configuration/property[contains(name,"key1.somestuff.someotherstuff")]' input-xml
<property><name>key1.somestuff.someotherstuff</name><value>value1</value></property>

假设我将您的输入文件修改为适当的 XML 结构:

$ cat modified-xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>
    <property>
        <name>key1.somestuff.someotherstuff</name>
        <value>value1</value>
    </property>
    <property>
        <name>key2.somestuff.someotherstuff</name>
        <value>value2</value>
    </property>
</configuration>

输出如下:-

<property>
        <name>key1.somestuff.someotherstuff</name>
        <value>value1</value>
    </property>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多