如何在JAXB中解组部分?

时间:2013-12-17 14:41:24

标签: java xml jaxb unmarshalling

我需要使用JAXB解组!DOCTYPE 部分,以便我可以获取file1和file2的值。

xml文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>

  <!DOCTYPE doc [
     <!ENTITY file1 SYSTEM "conf/files/file1.xml">
      <!ENTITY file2 SYSTEM "conf/files/file2.xml">
    ]>

    <appels>
      <appel>
         &file1;
      </appel>
      <appel>
         &file1;
       </appel>
    </appels>

java看起来像这样:

@XmlRootElement(name = "appels")
public class Appels implements Serializable {

private List<Appel> appel;

}

我需要得到 file1 = conf / files / file1.xml file2 = conf / files / file2.xml

这可能吗? 谢谢你的帮助

2 个答案:

答案 0 :(得分:3)

更新

以下内容将&file1;解析为conf/files/file1.xml文件的内容。

<!ENTITY file1 SYSTEM "conf/files/file1.xml">

以下内容会将&file3;解析为字符串conf/files/file3.xml

<!ENTITY file3 "conf/files/file3.xml">

输入文件

<强> input.xml中

这是您问题中XML文档的略微修改版本。我将其中一个&file1;更改为&file2;并添加了&file3;

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE doc [
    <!ENTITY file1 SYSTEM "conf/files/file1.xml">
    <!ENTITY file2 SYSTEM "conf/files/file2.xml">
    <!ENTITY file3 "conf/files/file3.xml">
 ]>
<appels>
    <appel>
         &file1;
    </appel>
    <appel>
         &file2;
    </appel>
    <appel>
         &file3;
    </appel>
</appels>

<强> CONF /文件/ file1.xml

<foo>Hello World</foo>

<强> CONF /文件/ file2.xml

我不打算将其作为XML文件,而只是添加文本。

Foo Bar

等效XML文件

就解析器而言,您的XML文档如下所示。请注意,&file1;&file2;已解析为其文件内容而&file3;未解析。

<?xml version="1.0" encoding="UTF-8"?>
<appels>
    <appel>
         <foo>Hello World</foo>
    </appel>
    <appel>
         Foo Bar
    </appel>
    <appel>
         conf/files/file3.xml
    </appel>
</appels>

演示代码

<强>演示

下面的演示代码将XML转换为对象,然后将其写回XML。当XML被解组为对象时,将解析实体。

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Appels.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum20637070/input.xml");
        Appels appels = (Appels) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(appels, System.out);
    }

}

<强>输出

请注意第一个appel元素是如何编组的。由于&file;已解析为XML片段,因此JAXB无法将其与我们映射的文本属性进行匹配。

<appels>
    <appel>
    </appel>
    <appel>
             Foo Bar
    </appel>
    <appel>
             conf/files/file3.xml
    </appel>
</appels>

Java模型

以下是我用于此示例的Java模型:

<强> Appels

import java.io.Serializable;
import java.util.List;
import javax.xml.bind.annotation.*;

@XmlRootElement(name = "appels")
@XmlAccessorType(XmlAccessType.FIELD)
public class Appels implements Serializable {

    private List<Appel> appel;

}

<强>阿佩尔

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
public class Appel {

    @XmlValue
    private String value;

}

答案 1 :(得分:0)