1

Given the file:

/// @file test.xml
<xml-fragment>
  <string name="foo" value="bar"/>
</xml-fragment>

the path xml-fragment/string and the attribute&value name="foo" to filter on, and the attribute value to query on, how should I get "bar"?

Using xmlstarlet, I have this:

xmlstarlet sel -t -m '/xml-fragment/string[attribute::name="foo"]' \
                  -v 'attribute::bar' test.xml

which appears to work, but I'm wondering if there is a better way?

I don't even require using xmlstarlet; I previously tried xmllint, xsltproc, and xpath, but couldn't get those to work.

Charles L Wilcox
  • 1,126
  • 8
  • 18

1 Answers1

1

I'm not sure if this is "better", but you could just use -v with the entire xpath. You could also use the @ abbreviated syntax.

Example (tested in windows; quotes might need to be changed)

xmlstarlet sel -t -v "/xml-fragment/string[@name='foo']/@value" test.xml

Any of the other tools you listed should work as well. If you're just getting a value, xsltproc might be overkill. As long as you're not using regex, you should be ok.

Community
  • 1
  • 1
Daniel Haley
  • 51,389
  • 6
  • 69
  • 95
  • Ah, see,I didn't even think I could trail the "queried" attribute 'value' after "filtering" for 'name="foo"'; I just assumed it had to be a nested element-name. – Charles L Wilcox Apr 14 '15 at 19:57