How to get JDOM2 Element text as a list if its content separated by its inner Elements?

StackOverflow https://stackoverflow.com/questions/16301776

  •  13-04-2022
  •  | 
  •  

Question

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!

Était-ce utile?

La solution

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();
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top