I’m trying to parse some Android XML using XmlSlurper. For a given child node, I want to detect whether or not an attribute with a particular namespace has been specified.
For example, in the following XML I would like to know whether the EditText node has had any attributes from the ‘b’ namespace declared:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:b="http://x.y.z.com">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
b:enabled="true" />
</LinearLayout>
I start by calling:
def rootNode = new XmlSlurper().parseText(text)
to get a handle on the root GPathResult. As I iterate through the children, I am given an instance of groovy.util.slurpersupport.NodeChild. On this class I can inspect the attributes by calling attributes() and in the case of EditText above, this will return the following map: [layout_width: "fill_parent", layout_height: "wrap_content", enabled: "true"].
This is all well and good. However, there doesn’t seem to be a way to query the namespace of a given attribute. Am I missing something here?
You can use
XmlParserrather thanXmlSlurperand do this:Which prints out
Edit
To use XmlSlurper, you first need to access the
namespaceTagHintsproperty from the root node using reflection:namespaceTagHintsis a property of GPathResult, which is a superclass ofNodeChild.You can then cross-reference this map to access the namespace prefix and print out the same result as above: