1

I try to create org.w3c.dom.Element which will contains both xml makr up and plain text

I need to get as a result something like this

<aff id="aff1"><label>2</label>Laboratories for Human Nutrition and</aff>

but I only get this

<aff id="aff1">&lt;label&gt;2&lt;/label&gt;Laboratories for Human Nutrition and</aff>

This code create aff xml node

Element aff = document.createElement("aff");
aff.setAttribute("id", "aff" + reference.id);
aff.setTextContent("<label>" + reference.label + "</label>" + reference.value);

Maybe there are some way to create dummy xml node for text only, which does not have tag, but allow to set its text content?

Oleh Kurpiak
  • 1,339
  • 14
  • 34
  • 1
    Possible duplicate of [Java DOM - Inserting an element, after another](https://stackoverflow.com/questions/3405055/java-dom-inserting-an-element-after-another) – Jongware Jan 28 '18 at 12:25

1 Answers1

1

setTextContent doesn't parse to DOM structure received text, but sets it as text node. Also to prevent potential structural mistakes it escapes XML special characters like < and > to &lt; and &gt;.

If you want your aff element to hold other elements you can't simply set it as text. You need to create separate elements and text nodes and then append them as child elements. So if you would like to have

<aff>
    <label>1</label>
    some text
    <label>2</label>
    another text
</aff>

you need code like

Element aff = doc.createElement("aff");

Element label1 = doc.createElement("label");
label1.setTextContent("1");
Text text1 = doc.createTextNode("some text");

Element label2 = doc.createElement("label");
label2.setTextContent("2");
Text text2 = doc.createTextNode("another text");


aff.appendChild(label1);
aff.appendChild(text1);
aff.appendChild(label2);
aff.appendChild(text2);
Pshemo
  • 122,468
  • 25
  • 185
  • 269