The Artima Developer Community
Sponsored Link

Python Buzz Forum
Using XPath with namespaced documents in dom4j

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Phillip Pearson

Posts: 1083
Nickname: myelin
Registered: Aug, 2003

Phillip Pearson is a Python hacker from New Zealand
Using XPath with namespaced documents in dom4j Posted: Feb 13, 2006 10:40 AM
Reply to this message Reply

This post originated from an RSS feed registered with Python Buzz by Phillip Pearson.
Original Post: Using XPath with namespaced documents in dom4j
Feed Title: Second p0st
Feed URL: http://www.myelin.co.nz/post/rss.xml
Feed Description: Tech notes and web hackery from the guy that brought you bzero, Python Community Server, the Blogging Ecosystem and the Internet Topic Exchange
Latest Python Buzz Posts
Latest Python Buzz Posts by Phillip Pearson
Latest Posts From Second p0st

Advertisement

In dom4j, once you have parsed a document, you can execute XPath expressions like so:

List list = doc.selectNodes("/path/to/elements/you/want");

The doc.selectNodes function is a thin wrapper around the jaxen XPath library. This saves you from having to write:

XPath xp = new org.jaxen.dom.Dom4jXPath("/path/to/elements/you/want");
List list = xp.execute(doc);

However, if the document uses namespaces, you have to tell jaxen about them, or you won't have any way of specifying namespaced elements. Until yesterday, I thought the only way to do this was:

XPath xp = new org.jaxen.dom.Dom4jXPath("/x:path/x:to/x:elements/x:you/x:want");
xp.addNamespace("x", "http://example.org/some-random-namespace");
List list = xp.execute(doc);

This is a pain in the ass - three lines of code every time you want to use XPath! I did it this way for a little while, but finally got sick of it yesterday and dug through the dom4j code until eventually finding out how to do it properly:

Map namespaces = new TreeMap();
namespaces.put("x", "http://example.org/some-random-namespace");
DocumentFactory.getInstance().setXPathNamespaceURIs(namespaces);

From then on, any time you call selectNodes on a dom4j Node object, you'll be able to use the x: namespace prefix. Much nicer!

Comment

Read: Using XPath with namespaced documents in dom4j

Topic: Python at work Previous Topic   Next Topic Topic: James Tauber : Python Web Frameworks and REST

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use