使用 xmllint 从 xml 文件中删除一行
Remove a block of lines from xml file using xmllint
我有 Test.xml 文件,其中包含以下内容。
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright XXXXXX -->
<services>
<service>
<ServiceName>service1</ServiceName>
<ServiceId>100</ServiceId>
</service>
<service>
<ServiceName>service2</ServiceName>
<ServiceId>200</ServiceId>
</service>
<service>
<ServiceName>service3</ServiceName>
<ServiceId>300</ServiceId>
</service>
</services>
根据服务名称,我必须删除该服务的整个块。
假设,service1 是我输入的名称,那么下面的块应该从 xml 中删除。
<service>
<ServiceName>service1</ServiceName>
<ServiceId>100</ServiceId>
</service>
我可以使用 awk/sed/grep
来做到这一点。但我应该在这里使用 xmllint 或其他一些 xml 解析实用程序。
经过研究,我可以使用以下命令关闭输出。但是,xml 版本和父标签(服务)在输出中丢失。
xmllint --xpath "//services/service[ServiceName!='service1']" Test.xml
xmlstarlet
解法:
xmlstarlet ed -d "//service[ServiceName='service1']" test.xml
输出:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright XXXXXX -->
<services>
<service>
<ServiceName>service2</ServiceName>
<ServiceId>200</ServiceId>
</service>
<service>
<ServiceName>service3</ServiceName>
<ServiceId>300</ServiceId>
</service>
</services>
//service[ServiceName='service1']
- xpath 表达式,选择具有子节点 ServiceName
且值为 service1
[=34 的 service
节点=]
修改文件"inplace" - 添加-L
选项:xmlstarlet ed -L ...
我有 Test.xml 文件,其中包含以下内容。
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright XXXXXX -->
<services>
<service>
<ServiceName>service1</ServiceName>
<ServiceId>100</ServiceId>
</service>
<service>
<ServiceName>service2</ServiceName>
<ServiceId>200</ServiceId>
</service>
<service>
<ServiceName>service3</ServiceName>
<ServiceId>300</ServiceId>
</service>
</services>
根据服务名称,我必须删除该服务的整个块。
假设,service1 是我输入的名称,那么下面的块应该从 xml 中删除。
<service>
<ServiceName>service1</ServiceName>
<ServiceId>100</ServiceId>
</service>
我可以使用 awk/sed/grep
来做到这一点。但我应该在这里使用 xmllint 或其他一些 xml 解析实用程序。
经过研究,我可以使用以下命令关闭输出。但是,xml 版本和父标签(服务)在输出中丢失。
xmllint --xpath "//services/service[ServiceName!='service1']" Test.xml
xmlstarlet
解法:
xmlstarlet ed -d "//service[ServiceName='service1']" test.xml
输出:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright XXXXXX -->
<services>
<service>
<ServiceName>service2</ServiceName>
<ServiceId>200</ServiceId>
</service>
<service>
<ServiceName>service3</ServiceName>
<ServiceId>300</ServiceId>
</service>
</services>
//service[ServiceName='service1']
- xpath 表达式,选择具有子节点ServiceName
且值为service1
[=34 的service
节点=]
修改文件"inplace" - 添加-L
选项:xmlstarlet ed -L ...