Reputation: 17
I have a XML format file with Added and Deleted tags.which will have many category except Birds and Humans.so below xml file will have many entries with different categories and many values in them as below
<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>
So here i need to count total no. of entries for each category in tags like as
Total No Of Added Birds=2
Total No Of Deleted Birds=2
Total No Of Added Humans=1
Upvotes: 0
Views: 316
Reputation: 88776
With xmlstarlet and this fixed XML file:
<?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>
Show added birds:
xmlstarlet select --template --value-of "//root/fixed[@NameCategory='Birds']/Added/value/@name" --nl file.xml
Output:
Duck Dove
Count added birds:
xmlstarlet select --template --value-of "count(//root/fixed[@NameCategory='Birds']/Added/value/@name)" file.xml
Output:
2
Count added and deleted birds and humans with one command:
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
Output:
2 2 1
With prefixed Text:
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
Output:
Total No Of Added Birds=2 Total No Of Deleted Birds=2 Total No Of Added Humans=1
See: xmlstarlet select --help
Upvotes: 2