I am trying to convert some code that is building XML in a StringBuilder to using dom4j.
Part of the code is generating something structured similar to this:
<foo myattribute="bar">i am some text<aninnertag>false</aninnertag>
(more text specific stuff <atag>woot</atag>)
and (another section <atag>woot again</atag> etc)
</foo>
I'm trying to figure out how to build this in dom4j. I could add elements for the inner tags but it's not going to generate it in a meaningful context. I could add it all as text but tags would get escaped.
How would one implement something like this in dom4j? Is it even possible?
This xml is terrible and I can't change it.
This is obviously incorrect in terms of output, but a basic example:
Element foo = new DefaultElement("foo");
foo.addText("i am some text" "(more text specific stuff " ")" "and (another section " " etc)");
foo.addElement("aninnertag").addText("false");
foo.addElement("atag").addText("woot");
foo.addElement("atag").addText("woot again");
CodePudding user response:
When you write one addText()
followed by three addElement()
calls you will get an XML content where you have the text at the beginning and the XML elements at the end. You have to interleave the addText()
and addElement()
calls like this:
Element foo = new DefaultElement("foo");
foo.addAttribute("myattribute", "bar");
foo.addText("i am some text");
foo.addElement("aninnertag").addText("false");
foo.addText("(more text specific stuff ");
foo.addElement("atag").addText("woot");
foo.addText(") and (another section ");
foo.addElement("atag").addText("woot again");
foo.addText(" etc)");
System.out.println(foo.asXML());
This will generate the following output:
<foo myattribute="bar">i am some text<aninnertag>false</aninnertag>
(more text specific stuff <atag>woot</atag>) and (another section
<atag>woot again</atag> etc)</foo>