If you have xmlstarlet installed, you can try:
me@home$ xmlstarlet sel -t -m "//testable" -v trigger -o "|" -v message -o "|" -m sales-info -v san-a -o "|" -v san-b -o "|" -v san-c -n test.xml
Trigger1|2012-06-14T00:03.54|no|no|no
Trigger2|2012-06-15T00:03.54|yes|yes|no
Breakdown of the command:
xmlstarlet sel -t
-m "//testable" # match <testable>
-v trigger -o "|" # print out value of <trigger> followed by |
-v message -o "|" # print out value of <message> followed by |
-m sales-info # match <sales-info>
-v san-a -o "|" # print out value of <san-a> followed by |
-v san-b -o "|" # print out value of <san-b> followed by |
-v san-c # print out value of <san-c>
-n # print new line
test.xml # INPUT XML FILE
To target tags that varies within <testable>
, you can try the following which returns the text of all leaf nodes:
ma@home$ xmlstarlet sel -t -m "//testable" -m "descendant::*[not(*)]" -v 'text()' -i 'not(position()=last())' -o '|' -b -b -n test.xml
Trigger1|2012-06-14T00:03.54|no|no|no
Trigger2|2012-06-15T00:03.54|yes|yes|no
Beakdown of the command:
xmlstarlet sel -t
-m "//testable" # match <testable>
-m "descendant::*[not(*)]" # match all leaf nodes
-v 'text()' # print text
-i 'not(position()=last())' -o '|' # print | if not last item
-b -b # break out of nested matches
-n # print new line
test.xml # INPUT XML FILE
If you do not have access to xmlstarlet
, then do look up what other tools you have at your disposal. Other options would include xsltproc (see mzjn's answer) and xpath.
If those tools are not available, I would suggest using a higher level language (Python, Perl) which gives you access to a proper XML library.
While it is possible to parse it manually using regex
, such a solution would not be ideal† especially with inconsistent inputs. For example, the following (assuming you have gawk
and sed
) takes your input and should spits out the expected output:
me@home$ gawk 'match($0, />(.*)</, a){printf("%s|",a[1])} /<\/testable>/{print ""}' test.xml | sed 's/.$//'
Trigger1|2012-06-14T00:03.54|no|no|no
Trigger2|2012-06-15T00:03.54|yes|yes|no
However, this would fail miserably if the input format changes and is therefore not a solution I would generally recommend.