Reputation: 473
I'm attempting to retrieve the value of a single element in an XML file. I've truncated the XML to the relevant bit:
<opt>
<security>
<check>
<secure>true</secure>
</check>
</security>
</opt>
I'm trying to retrieve 'true' from the 'secure' element.
I have the following code:
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder=domFactory.newDocumentBuilder();
Document doc = builder.parse(file);
XPath xpath=XPathFactory.newInstance().newXPath();
XPathExpression expr=xpath.compile("//opt/security/check/secure/text()");
Object result = expr.evaluate(doc, XPathConstants.STRING);
logger.warn(result.toString());
I'm just trying to get any value for now, and I'll change the String to Boolean once I get this to work.
My output is blank, I've tried a bunch of different things, including following a tutorial and using NodeLists (although that didn't make very much sense to me since this is a unique element). Am I missing something?
Thanks!
Upvotes: 2
Views: 461
Reputation: 108899
Your code works using the default XPath implementation in my JVM (Sun/Oracle Java on Windows):
>java -version
java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) Client VM (build 16.3-b01, mixed mode)
The double forward-slash isn't necessary in the sample document; as MSDN notes:
An expression that uses the double forward slash (//) indicates a search that can include zero or more levels of hierarchy.
I wonder if this is a namespace issue:
domFactory.setNamespaceAware(true);
You could try omitting this line or providing a NamespaceContext.
Upvotes: 2