如何使用Jaxb将xml转换为Java类?

时间:2019-07-09 16:40:41

标签: java xml jaxb xml-attribute

我知道这里有很多内容,但是我无法完成特定的结构:

<ECG
ACQUISITION_TIME="20190625101706"
ACQUISITION_TIME_XML="2019-06-25T10:17:06"
ROOM=""
LOCATION="AMB"
COMMENT="ANDRESA"
AGE="45"
AGE_UNITS="Y"
HEIGHT="164"
HEIGHT_UNITS="C"
WEIGHT="85"
WEIGHT_UNITS="K"
NUM_QRS="10"
AVERAGE_RR="1013"
VENT_RATE="59"
TECHNICIAN=""
SYSTOLIC_BP="000"
DIASTOLIC_BP="000"
SEQUENCE_NUMBER="17617">

<DEMOGRAPHIC_FIELDS>
<DEMOGRAPHIC_FIELD ID="2" LABEL="Solic.:" VALUE="172001" UNITS="" />
<DEMOGRAPHIC_FIELD ID="7" LABEL="Nome:" VALUE="PAC TEST2" UNITS="" />
<DEMOGRAPHIC_FIELD ID="1" LABEL="Sobre:" VALUE="SOBROME2" UNITS="" />
<DEMOGRAPHIC_FIELD ID="26" LABEL="Prontuário" VALUE="SMO" UNITS="" />
<DEMOGRAPHIC_FIELD ID="4" LABEL="Sexo:" VALUE="Female" UNITS="" />
<DEMOGRAPHIC_FIELD ID="3" LABEL="" VALUE="45" UNITS="Y" />
<DEMOGRAPHIC_FIELD ID="9" LABEL="Alt:" VALUE="164" UNITS="C" />
<DEMOGRAPHIC_FIELD ID="10" LABEL="Peso:" VALUE="85" UNITS="K" />
<DEMOGRAPHIC_FIELD ID="14" LABEL="Local:" VALUE="AMB" UNITS="" />
<DEMOGRAPHIC_FIELD ID="17" LABEL="Obs.:" VALUE="ANDRESA" UNITS="" />
</DEMOGRAPHIC_FIELDS>

<SITE ID="1"/>

<SUBJECT
LAST_NAME="SOBRENOME2"
FIRST_NAME="PACIENTE TESTE2"
GENDER="Female"
ID="11402872001"
DOB="00000000"
DOB_XML="0000-00-00"/>

</ECG>

这是我需要转换的xml文件的一部分,我对于应该是什么元素,属性或对象感到非常困惑

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

  @XmlElement(name = "DEMOGRAPHIC_FIELDS")
  private List<MortaraXmlDemographicField> demographicField;

  @XmlElement(name = "SITE")
  private String site;

  @XmlElement(name = "SUBJECT")
  private String subject;
}

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

  @XmlAttribute(name = "ID")
  private String id;

  @XmlAttribute(name = "LABEL")
  private String label;

  @XmlAttribute(name = "VALUE")
  private String value;

  @XmlAttribute(name = "UNITS")
  private String units;
}

这就是我开始代码的方式,但是我对如何正确地构建代码感到非常困惑。如何处理没有数据但只有属性的标签?和包含相同标签列表的标签?是否有一些我需要的例子?感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

理想情况下,您应该为此XML使用xsd模式。如果没有,请为此XML创建一个。然后使用该xsd模式,可以从命令行从Java使用xjc实用工具生成Java类。