如何在 JAXB 中构建 XML 结构化的 Java 对象?

如何在 jaxb 中构建 xml 结构化的 java 对象?

使用jaxb生成映射xml结构的java对象

问题:

如何使用jaxb构建符合以下xml结构的java对象?

<speak><voice name="zh-cn-yunxineural">我是
        <break time="1000ms"></break>
        张三
    </voice><voice name="zh-cn-xiaoxiaoneural">他是
        <break time="100ms"></break>
        李四
    </voice></speak>

答案:

将以下代码添加到现有对象模型:

@data
@xmlaccessortype(xmlaccesstype.field)
@xmlrootelement(name = "voice")
public class voicexbj {
 
    @xmlattribute
    private string name;
 
    @xmlmixed
    @xmlelementref(type = breakxbj.class)
    private list<object> content;
 
}</object>
@data
@xmlaccessortype(xmlaccesstype.field)
@xmlrootelement(name = "break")
public class breakxbj {
 
    @xmlattribute
    private string time;
}

修改以下测试用例:

@slf4j
public class ssmltest {
 
    @test
    public void test1() {
        speakxbj xbj = new speakxbj();
        list<voicexbj> voicelist = new arraylist();
        voicexbj voice = new voicexbj();
        voice.setname("yunxi");
        breakxbj breakxbj = new breakxbj();
        breakxbj.settime("1000ms");
        list<object> breaklist = new arraylist();
        breaklist.add("我是");
        breaklist.add(breakxbj);
        breaklist.add("张三");
        voice.setcontent(breaklist);
        voicelist.add(voice);
 
        voicexbj voice1 = new voicexbj();
        voice1.setname("aixia");
        breakxbj breakxbj1 = new breakxbj();
        breakxbj1.settime("100ms");
        list<object> breaklist1 = new arraylist();
        breaklist1.add("他是");
        breaklist1.add(breakxbj1);
        breaklist1.add("李四");
        voice1.setcontent(breaklist1);
        voicelist.add(voice1);
 
        xbj.setvoice(voicelist);
        system.out.println(xmlutil.converttoxml(xbj));
    }
}</object></object></voicexbj>

输出结果:

<?xml version="1.0" encoding="GBK" standalone="yes"?><speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="http://www.w3.org/2001/mstts" xmlns:emo="http://www.w3.org/2009/10/emotionml" xml:lang="zh-CN"><voice name="zh-CN-YunxiNeural">我是
        <break time="1000ms"></break>张三</voice><voice name="zh-CN-XiaoxiaoNeural">他是
        <break time="100ms"></break>李四</voice></speak>

以上就是如何在 JAXB 中构建 XML 结构化的 Java 对象?的详细内容,更多请关注其它相关文章!