Thursday, August 7, 2008

Getting Fully Qualified (attributes, that is)

There's a lot of good examples out there on using GPath to read XML, but I couldn't find anything on a specific use case I had. While it's simple to access namespace-qualified elements, I was bereft of an example showing how to access a namespace-qualified attribute. Is this a black art, or is my Google-Fu weak? Hopefully neither. In any case, I figured out a way to it, and it's dirt simple.

Just use the Node.attribute() method, and pass it the QName of the attribute. You'll just need to define a namespace, like:

def atom = new Namespace("http://www.w3.org/2005/Atom")
def rdf = new Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf")


And then you're ready to go. For example, you have a document with a title node with an RDF "about" attribute. title[@about] won't get it, because the attribute is behind the namespace. But this will:


def parser = new XmlParser(false, true) def feed = parser.parse(feedDoc)
def about = feed.title.attribute(rdf.about)


The nice thing about this is it works the same way everywhere, e.g.,
def ed = root[foaf.Person].find {
it.attribute(rdf.about) == "$edRef"
}[foaf.name].text()


And so on. Have fun!