1

I want to build up a String from an XML-file in Java, using JDOM2. The XML-file snippet what I want to process looks like the following:

...
<title>
  usefuldatapart1
  <span profile="id1"> optionaldata1 </span>
  <span profile="id2"> optionaldata2 </span>
  <span profile="id3"> optionaldata3 </span>
  usefuldatapart2
</title>
...

The element 'title' contains useful textual content for me separated into several parts with inner Elements, and if any of the profiles turn active I have to insert the content of the inner Element amongst the right parts (only one can be active at a time but in this case it's not important).

Is there any elegant way to get the Element text back as an array of Strings for further operations?

Or if I get this on a wrong way how could I do it properly?

(Currently suffering with Element's 'getText' and 'getContent' methods, and the basics of 'XMLOutputter')

Thanks for any help!

Syry
  • 13
  • 4

1 Answers1

0

There are potentially multiple ways to do this. One of which is using XPaths, but perhaps it's just simpler to use a descendants iterator and a StringBuilder, and a check on the ancestry of each text node....

For example (and I'm typing in by hand, not validating this...):

public String getTitleText(final Element title) {
    final StringBuilder sb = new StringBuilder();
    for (final Text txt : title.getDescendants(Filters.text())) {
        final Element parent = txt.getParentElement();
        if (parent == title || 
                parent.getAttributeValue("active", "not").equals("true")) {
            sb.append(txt.getValue());
        }
    }
    return sb.toString();
}
rolfl
  • 17,539
  • 7
  • 42
  • 76
  • It works properly, and being so simple, Thanks for the help! :) – Syry May 02 '13 at 13:11
  • The site cannot allow me to improve the post, but the only bug in the code is 'Filters.text()' instead of 'Filter.text()'. Thanks again! – Syry May 02 '13 at 13:18