tags:

views:

74

answers:

2

This is a java question, btw.

I'm using xPath and everything works great until I get to the last point where I'm looking at the node set that I've sought and I need to do a really ugly evaluation to see if the node I'm dealing with is of type ELEMENT or TEXT before I can get its value. I was wondering if there's a method along the lines of the one I wrote beneath that will get me the value.

XPathExpression expr = inFeed.getXpath().compile(xPathEx);
Object result = expr.evaluate( rootNode, XPathConstants.NODESET);
NodeList nodeList = (NodeList)result;
ret = "";
for(int i = 0; i< nodeList.getLength() ; i++){
    ret += getNodeValue(nodeList.item(i)) + ",";
}

so... see the getNodeValue() method? It gets me the string that's inside that node and if the node happens to not be of type TEXT it goes looking for children and when it finds a TEXT node it returns that.

There MUST be a Node native way to do this that I'm overlooking, right?

+2  A: 

bah! it was right there... Node.getTextContent(). <roseanne-roseannadanna> nevermind! </roseanne-roseannadanna>

Dr.Dredel
+1  A: 

Using dom4j, you can so it pretty simply...

import org.dom4j.Document;
import org.dom4j.io.SAXReader;

SAXReader reader = new SAXReader();
Document doc = reader.read('example.xml');
StringBuilder ret = new StringBuilder();
for (Node n : doc.selectNodes('//book')) {
  if (ret.length() > 0) {
    ret.append(", ");
  }
  ret.append(n.getText());
}

println ret.toString();

(NOTE: the syntax is groovy, but it works the same in Java.)

The selectNodes() method takes an xpath expression. The getText() method returns all textual content of a Node, including its children.

Drew Wills