Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the number of elements in an XML document using xmlstarlet in BASH?

I need to count the number of times an element occurs within an XML document. The element I need to count is called 'ThreadGroup'

Elelement to count:

<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group" enabled="true">

There are three ThreadGroup elements in the following XML. How can we count them using xmlstarlet?

Test XML

<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="2.8" jmeter="2.13 r1665067">
<hashTree>
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Test Plan" enabled="true">
  <stringProp name="TestPlan.comments"></stringProp>
  <boolProp name="TestPlan.functional_mode">false</boolProp>
  <boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
  <elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
    <collectionProp name="Arguments.arguments"/>
  </elementProp>
  <stringProp name="TestPlan.user_define_classpath"></stringProp>
</TestPlan>
<hashTree>
  <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group" enabled="true">
    <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
  </ThreadGroup>
  <hashTree/>
  <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group" enabled="true">
    <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
  </ThreadGroup>
  <hashTree/>
  <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group" enabled="true">
    <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>

  </ThreadGroup>
  <hashTree/>
</hashTree>

like image 376
user1654528 Avatar asked Mar 13 '23 03:03

user1654528


1 Answers

Try with count() function, like:

xmlstarlet sel -t -c "count(//ThreadGroup)" xmlfile

In a well-formed xml file (not your case) it would yield:

3
like image 182
Birei Avatar answered Apr 08 '23 06:04

Birei