Problems with XPathExpression on memory built Document
Hi,
I'm working with XML documents that are built in memory. This seems to work jsut fine but I've got a problem while trying to evaluate an XPathExpression on the document. When I do it returns a null result. Here's an example of what I'm trying to do and maybe someone might have an idea how I can fix this issue:
The XML looks similar to this:
Code :
<mta>
<subject>Some Text</subject>
<!-- other stuff under here as well -->
</mta>
My code:
Code :
Object results;
NodeList ndlst;
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//mta/subject/text()");
results = expr.evalutate(doc, XPathConstants.NODESET);
ndlst = (NodeList) results;
The NodeList should have one node in it but it if I were to request a .getLength() from it then it returns 0
As I said the document is built in memory (not read from a flat file). I have tested this XPath expression on a flat file and it works. Only when the document is built in memory do I have this problem.
Re: Problems with XPathExpression on memory built Document
This works on a flat file for me as well.
Could you show us the code you use to build the document into memory?
// Json
Re: Problems with XPathExpression on memory built Document
Actually I figured out the problem this morning. The problem was that I was adding the information with the wrong function. I had assumed that since I was getting the information with the getNodeValue() function I should use setNodeValue() to add the data.
I found that I need to use the setTextContent() function to create the document.
Re: Problems with XPathExpression on memory built Document
Aha, good job you sorted it out, myself I prefer to use the JDOM stuff along with the SAXBuilder to do XML stuff or sometimes I like the Apache Commons Configuration to load XML data.
// Json
Re: Problems with XPathExpression on memory built Document
I'm new to Java coming from more from Microsoft .NET and using the msxml for handling DOM and XPath. So I haven't had the chance to really get to work much with the other XML parsers available with Java.