Search code examples
javaxmldom4j

Java, dom4j: how to add inline element (b, i, u) in the middle of text


I have thought this matter enough. I should be able to do this kind of XML:

    <root>
     <text>I am <b>text</b>, alright?</text>
    </root>

My question is simple: how an earth Im able to do that inline-element (b, i, u) in the middle of text by using dom4j or should I use an alternative way, when making this kind of inline elements?

It is obvious for me, that this won't work:

    Element e = rootelem.addElement("text");
    e.addElement("b").setText("text");

Anyone? Please tell me how... This drives me insane. :D


Solution

  • It's simple. Just don't use setText.

    There is a difference between "setting the text value of a node" (which eradicates all other content the node would have) and "adding a text node to a node" (which allows intermixing text nodes with other node types).

    Use addText for the latter.

    Element text = rootelem.addElement("text");
    
    text.addText("I am ");
    text.addElement("b").addText("text");
    text.addText(", alright?");
    

    Interface Element, method addText: Adds a new Text node with the given text to this element.


    As an aside, naming an element <text> when in fact it does not contain text at all (but markup) is a bit unfortunate. Maybe something like <html> would be a wiser choice.