0

Assuming I have such an XML file:

<view>
  <field table="alice" name="fish"/>
  <field id="confirmation" controlType="button" enabled="some-condition">
    <title>Confirm...</title>
  </field>
  <field table="bob" name="cat"/>
  <field table="bob" name="dog" hidden="true"/>
</view>

I want to output all its fields, but the output is conditional on the attributes which are present.

Expected result:

field 'alice.fish'
button "Confirm..." (enabled: some-condition)
field 'bob.cat'
field 'bob.dog' (hidden: true)

Current result:

field 'alice.fish' (hidden: )
field '.' (hidden: )
field 'bob.cat' (hidden: )
field 'bob.dog' (hidden: true)
 "" (enabled: )
button "confirm" (enabled: some-condition)
 "" (enabled: )
 "" (enabled: )

via 2 calls to XmlStarlet:

xmlstarlet sel -t -m "//field" -o "field '" -v "@table" -o "." -v "@name" -o "' (hidden: " -v "@hidden" -o ")" -n $1
xmlstarlet sel -t -m "//field" -v "@controlType" -o " \"" -v "@id" -o "\" (enabled: " -v "@enabled" -o ")" -n $1

Is is possible to turn the 3 different types of results inside 1 call to XmlStarlet, so that the fiels stay presented in their original order?

user3341592
  • 1,419
  • 1
  • 17
  • 36

1 Answers1

0

You need to use the --if option (--break indicates end of current control structure).

xmlstarlet sel --text -t -m "//field" \
    --if "@controlType='button'" \
        -v "@controlType" -o " \"" -v "title" -o "\" (enabled: " -v "@enabled" -o ")" \
    --else \
        -o "field '" -v "@table" -o "." -v "@name" -o "'" \
        --if "@hidden" -o " (hidden: " -v "@hidden" -o ")" --break \
    --break \
    -n "$1"
npostavs
  • 4,877
  • 1
  • 24
  • 43
  • Almost there! What I'd like is the text between the `title` tags, in the case of the button. Can you show me how to get it? -- Not a real XPath newbie here. – user3341592 Feb 27 '16 at 20:34
  • I meant: a real XPath newbie here! – user3341592 Feb 27 '16 at 21:16
  • Just replace `@id` with `title`. – npostavs Feb 28 '16 at 00:28
  • Very last question: is it possible to capitalize (first letter only) programmatically the found "controlType" (here: "button" -> "Button")? – user3341592 Feb 28 '16 at 10:53
  • Hmm, possibly you could try `-v "translate(substring(@controlType,1,1),'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')" -v "substring(@controlType,2)"` instead of `-v "@controlType"`, but you're probaby off better using `sed` on the output. – npostavs Feb 28 '16 at 14:09