使用 Java 创建 xml 时如何在标签之间添加信息

How to add information in-between tags when creating an xml with Java

我想创建一个 XML 文件,如下所示:

<fml-apml>
<bml>
    <speech id="s1" start="0.0" language="english" voice="openmary" type="SAPI4" text="">
        <description level="1" type="xxx">
            <reference>tmp/from-fml-apml.pho</reference>
        </description>

        <tm id="tm1"/>
             TEXT 1
        <tm id="tm2"/>
             TEXT 2
        <tm id="tm3"/>  
             TEXT 3
        <tm id="tm4"/>
             TEXT 4
        <tm id="tm5"/>  

    </speech>
</bml>
<fml>
   <some more code> 
</fml>
</fml-apml>

问题是我正在使用 DocumentBuilder 库,但我找不到在中间标记中插入 "Text XX" 的方法。有没有办法这样做或者我应该从头开始写整个 XML?

明确一点,您不想在任何标签中包含标签之间的文本?看起来格式不正确 XML

您可以使用Document.createTextNode。例如

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

Element speechElem = doc.createElement("speech");
doc.appendChild(speechElem);

speechElem.appendChild(doc.createElement("tm"));
speechElem.appendChild(doc.createTextNode("TEXT 1"));
speechElem.appendChild(doc.createElement("tm"));
speechElem.appendChild(doc.createTextNode("TEXT 2"));
speechElem.appendChild(doc.createElement("tm"));

结果

<speech>
    <tm/>TEXT 1<tm/>TEXT 2<tm/>
</speech>