[jdom-interest] setText() to replace children?

Elliotte Rusty Harold elharo at metalab.unc.edu
Tue Jul 10 08:25:11 PDT 2001


At 10:48 AM -0400 7/10/01, Alex Rosen wrote:
>The only problem with all these proposals is the lack of symmetry. If you get
>text by calling getText(), it's natural to set it via setText(), and if that's
>not the name of the method, you have to go looking for it, and figure out if it
>really does what you want it to do. Similarly for setContent() and
>setChildren(). Whether that's a good enough reason to keep the current state of
>things, I don't know. I really like the intuitiveness of setText(), though. In
>the common case where you don't have mixed content, it feels a lot more
>natural.
>

Now that you mention it I don't like getText() either. It has the same problem setText() does: it really doesn't make sense when the element contains mixed content or even a child element. It violates the principal of least surprise. For example, consider this XHTML element:

<p>
  Do <strong>NOT</strong> eat the yellow snow!
</p>

Currently invoking getText() on the p element would produce the string "Do eat  the yellow snow!" This is very unexpected. Worse yet, it might not be noticed at first glance. It is a hidden bug that could produce potentially catastrophic results.

I propose that the getText() method be rewritten to return the concatenation of all text inside the element, regardless of child elements; i.e. that it should recurse through children. This is essentially the XPath value of the element. This will produce identical results when the element does not contain mixed content, but much more sensible results when the element does contain mixed content.
-- 

+-----------------------+------------------------+-------------------+
| Elliotte Rusty Harold | elharo at metalab.unc.edu | Writer/Programmer |
+-----------------------+------------------------+-------------------+ 
|          The XML Bible, 2nd Edition (Hungry Minds, 2001)           |
|              http://www.ibiblio.org/xml/books/bible2/              |
|   http://www.amazon.com/exec/obidos/ISBN=0764547607/cafeaulaitA/   |
+----------------------------------+---------------------------------+
|  Read Cafe au Lait for Java News:  http://www.cafeaulait.org/      | 
|  Read Cafe con Leche for XML News: http://www.ibiblio.org/xml/     |
+----------------------------------+---------------------------------+



More information about the jdom-interest mailing list