Hamed Sanaei
Hamed Sanaei

Reputation: 131

Check for attribute existence in jdom2 for a given xml in Java

I am trying to find XML node's which has an attributed called "CommunityOwnedDate" in an XML node in java. I am using jdom2. Some node doesn't have that node and i am trying to find that using jdom2. Is there any other straightforward way to do this?

import org.jdom2.*;
import org.jdom2.input.SAXBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;

String xml = "<row Id="4" PostTypeId="1" AcceptedAnswerId="7" CreationDate="2008-07-31T21:42:52.667" Score="322" ViewCount="21888"  AnswerCount="13" CommentCount="1" FavoriteCount="27" CommunityOwnedDate="2012-10-31T16:42:47.213" />"
SAXBuilder saxBuilder = new SAXBuilder();

Document doc = saxBuilder.build(new StringReader(xml))
Element row = doc.getRootElement();
XPathFactory xpfac = XPathFactory.instance();
XPathExpression xp = xpfac.compile("//row[@CommunityOwnedDate]");
var xpathObjects= xp.evaluate(doc);

And then i want to check it like this:

if(xpathObjects != null){
                //do something
            }

consequently, it throws this exception: java.lang.ClassNotFoundException: org.jaxen.NamespaceContext at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)

Upvotes: 0

Views: 383

Answers (2)

Michael Kay
Michael Kay

Reputation: 163262

I think you have some kind of installation/configuration problem. JDOM2 uses Jaxen as its native XPath processor, and it looks to me as if Jaxen isn't on your classpath, or isn't being picked up as your XPathFactory.

You might like to know that if you want to use XPath 3.1 expressions, you can use Saxon (PE or higher) against a JDOM2 document as an alternative to Jaxen.

Upvotes: 1

Hamed Sanaei
Hamed Sanaei

Reputation: 131

There is another way to circumvent the NullPointerExceptionerror. I used the method below:

getAttributeValue(java.lang.String attname, java.lang.String def)

This returns the attribute value for the attribute with the given name and within no namespace, or the passed-in default if there is no such attribute.

Upvotes: 0

Related Questions