[jdom-interest] Element comparison in XML document

Lighton Phiri lighton.phiri at gmail.com
Fri Apr 13 01:22:19 PDT 2012


Is there an easier way of checking if an element exists in an XML
file? I tried to use the List function 'contains' to do my comparison,
but it seems to fail; checked the Element class for appropriate
methods, but nothing there. The closest I came to finding something
similar on markmail.org is an old article [1] that isn't quite
helpful. The only workaround I can think of at the moment is a
recursive walk-through to check the textual content of each element,
but something tells me there has to be a built-in mechanism for doing
this.

Code snippet

Element hasPartNode = new Element("hasPart",
Namespace.getNamespace("dcterms", "http://purl.org/dc/terms/"));
hasPartNode.addContent("A1_4_001");

// This prints false
System.out.println(rootNode.getChildren("hasPart",
Namespace.getNamespace("dcterms",
"http://purl.org/dc/terms/")).contains(hasPartNode));

Input XML document

<resource xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:dcterms="http://purl.org/dc/terms/">
  <dc:title>Notebooks</dc:title>
  <dcterms:hasPart>A1_4_001</dcterms:hasPart>
  <dcterms:hasPart>A1_4_002</dcterms:hasPart>
  <dcterms:hasPart>A1_4_003</dcterms:hasPart>
</resource>

[1] http://markmail.org/message/s7le3js7r5vub7oy

-- Phiri


More information about the jdom-interest mailing list