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!

4

1 回答 1

0

可能有多种方法可以做到这一点。其中之一是使用 XPaths,但使用后代迭代器和 StringBuilder 以及检查每个文本节点的祖先可能更简单......

例如(我是手动输入,而不是验证...):

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();
}
于 2013-04-30T15:51:00.700 回答