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

妖精的绣舞 提交于 2019-12-11 01:01:40

问题


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>


回答1:


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


来源:https://stackoverflow.com/questions/35669280/how-can-i-count-the-number-of-elements-in-an-xml-document-using-xmlstarlet-in-ba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!