Как я могу подсчитать количество элементов в XML-документе, используя xmlstarlet в BASH?

Мне нужно подсчитать, сколько раз элемент встречается в XML-документе. Элемент, который мне нужно посчитать, называется «ThreadGroup».

Элемент для подсчета:

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

В следующем XML есть три элемента ThreadGroup. Как мы можем их посчитать с помощью xmlstarlet?

Тестовый 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>


person user1654528    schedule 27.02.2016    source источник


Ответы (1)


Попробуйте использовать функцию count(), например:

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

В правильно сформированном файле xml (не в вашем случае) это даст:

3
person Birei    schedule 27.02.2016