我正在尝试将一些在StringBuilder中构建XML的代码转换为使用dom4j。
代码的一部分是生成类似于以下结构的东西:
<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>
我正试图弄清楚如何在dom4j中构建这个。我可以为内部标记添加元素,但它不会在有意义的上下文中生成它。我可以将其全部添加为文本,但标签会被转义。
如何在dom4j中实现这样的东西?这可能吗?
这个xml很糟糕,我无法更改它。
就输出而言,这显然是不正确的,但一个基本的例子是:
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");
当您编写一个addText()
,然后编写三个addElement()
调用时,您将获得一个XML内容,其中文本在开头,XML元素在结尾。您必须像这样交错addText()
和addElement()
调用:
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());
这将生成以下输出:
<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>