[ACCEPTED]-Testing for an XML attribute-xmlstarlet

Accepted answer
Score: 38

This will select the foos with no src attribute.


For 13 the other two tasks, I would use a mix of 12 the expressions pointed out by @TOUDIdel 11 and @Dimitre Novatchev: /root/foo[@src and string-length(@src)=0] for foos with 10 an empty src, and /root/foo[@src and string-length(@src)!=0] for foos with an src with content 9 in it.

As an aside, I would avoid using the 8 "anywhere" selector, // (not to mention the 7 * wildcard), unless you're sure that this 6 is specifically what you need. // is like 5 making your very eager dog sniff a piece 4 of cloth and telling it, "bring me everything 3 that smells like this, wherever you find 2 it". You won't believe the weird crap it 1 can decide to bring back.

Score: 16

I want to know which elements have a src attribute, which are empty and 9 which have values.

Elements having a @src attribute 8 which is empty (no string-value):


Elements 7 having a @src attribute which has value (string-value):


From 6 http://www.w3.org/TR/xpath/#section-String-Functions

A node-set is converted to a string by returning 5 the string-value of the node in the node-set 4 that is first in document order. If the 3 node-set is empty, an empty string is returned.

From 2 http://www.w3.org/TR/xpath/#function-boolean

A string is true if and only if its length 1 is non-zero.

Score: 6

/root/foo[string-length(@src)!=0] return all foo elements have non empty value.

Unfortunately 2 /root/foo[string-length(@src)=0] indicates elements which don't have src attribute 1 and also elements have src attribute but empty.

Score: 5


//*[@src and not(string-length(@src))]

This selects all elements in the XML document 10 that have a src attribute whose string-value 9 has length of zero.

//*[@src and string-length(@src)]

This selects all elements 8 in the XML document that have a src attribute 7 whose string-value has length that is not 6 zero.

//*[@src and string-length(normalize-space(@src))]

This selects all elements in the XML 5 document that have a src attribute whose string-value 4 after excluding the starting and ending 3 whitespace has length that is not zero.


This 2 selects all elements in the XML document 1 that don't have a src attribute.

More Related questions