不计算不同xml标签中的条目

时间:2017-12-30 05:12:18

标签: xml bash awk grep

我有一个带有已添加和已删除标签的XML格式文件。除了鸟类和人类之外,还有许多类别。因此,xml文件下面会有许多不同类别的条目,其中有很多值,如下所示

<xml version=1.0>
   <NameCategory="Birds">
       <Added>
         <value name="Duck" count="1"></value>
         <value name="Dove" count="2"></value>
       </Added>
       <Deleted>
         <value name="crow" count="1"></value>
         <value name="crane" count="10"></value>
       </Deleted>
   </NameCategory>
   <NameCategory="Humans">
         <value name="john" count="1"></value>
   </NameCategory>
</xml>

所以在这里我需要计算总数。标签中每个类别的条目,如

Total No Of Added Birds=2
Total No Of Deleted Birds=2
Total No Of Added Humans=1

1 个答案:

答案 0 :(得分:2)

使用xmlstarlet和这个固定的XML文件:

<?xml version="1.0"?>
<root>
  <fixed NameCategory="Birds">
    <Added>
      <value name="Duck" count="1"/>
      <value name="Dove" count="2"/>
    </Added>
    <Deleted>
      <value name="crow" count="1"/>
      <value name="crane" count="10"/>
    </Deleted>
  </fixed>
  <fixed NameCategory="Humans">
    <value name="john" count="1"/>
  </fixed>
</root>

显示添加的鸟类:

xmlstarlet select --template --value-of "//root/fixed[@NameCategory='Birds']/Added/value/@name" --nl file.xml

输出:

Duck
Dove

计算添加的鸟类:

xmlstarlet select --template --value-of "count(//root/fixed[@NameCategory='Birds']/Added/value/@name)" file.xml

输出:

2

用一个命令计算添加和删除的鸟类和人类:

xmlstarlet select --template \
   --value-of "count(//root/fixed[@NameCategory='Birds']/Added/value/@name)" --nl \
   --value-of "count(//root/fixed[@NameCategory='Birds']/Added/value/@name)" --nl \
   --value-of "count(//root/fixed[@NameCategory='Humans']/value/@name)" --nl file.xml

输出:

2
2
1

带有前缀文字:

xmlstarlet select --template \
   --value-of "concat('Total No Of Added Birds=',count(//root/fixed[@NameCategory='Birds']/Added/value/@name))" --nl \
   --value-of "concat('Total No Of Deleted Birds=',count(//root/fixed[@NameCategory='Birds']/Deleted/value/@name))" --nl \
   --value-of "concat('Total No Of Added Humans=',count(//root/fixed[@NameCategory='Humans']/value/@name))" --nl file.xml

输出:

Total No Of Added Birds=2
Total No Of Deleted Birds=2
Total No Of Added Humans=1

请参阅:xmlstarlet select --help