Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for an XML attribute

I have a piece of XML like so:

<root>     <foo src=""/>     <foo src="bar"/>     <foo /> </root> 

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

The furthest I have come is with

$ xmlstarlet sel -t -m '//foo' -v @src -n foo.xml   bar 

Though that doesn't tell me the third foo is missing the attribute.

like image 624
hendry Avatar asked Apr 07 '11 11:04

hendry


People also ask

How do you check if a specific attribute exists or not in XML?

The hasAttribute() method returns TRUE if the current element node has the attribute specified by name, and FALSE otherwise.

What is an XML attribute?

The XML attribute is a part of an XML element. The addition of attribute in XML element gives more precise properties of the element i.e, it enhances the properties of the XML element.

Why do you avoid XML attributes?

Why should we avoid XML attributes. Attributes cannot contain multiple values but child elements can have multiple values. Attributes cannot contain tree structure but child element can. Attributes are not easily expandable.

Is XML attributes must be quoted?

XML elements can have attributes in name/value pairs; however, the attribute value must always be quoted. In the incorrect document, the date attribute in the note element is not quoted.


1 Answers

This will select the foos with no src attribute.

/root/foo[not(@src)] 

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

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

like image 173
Jean-François Corbett Avatar answered Oct 18 '22 05:10

Jean-François Corbett