如何自定义映射xml到JAXB中的类

时间:2013-06-24 16:42:45

标签: java xml jaxb

我正在尝试处理以下xml:

<?xml version="1.0" encoding="UTF-8"?>
<operation name="GET_NOTES">
  <result>
    <status>Success</status>
    <message>Notes details fetched successfully</message>
  </result>
<Details>
  <Notes>
    <Note URI="http://something/24/notes/302/">
      <parameter>
        <name>ispublic</name>
        <value>false</value>
      </parameter>
      <parameter>
        <name>notesText</name>
        <value>Note added to the request</value>
      </parameter>
      ...
    </Note>
    ...
  </Notes>
<Details>
</operation>

这有很多无用的东西,所以我试图映射到类似的东西:

public class Notes {
  public List<Note> notes;
}

public class Note {
  public String notesText; //value of parameter with name notesText
  public Boolean isPublic; //value of parameter with name ispublic
}

这是否可以使用JAXB,你会怎么做呢?

1 个答案:

答案 0 :(得分:0)

JAXB只是忽略了bean中不存在的xmlelement。或者,使用@XmlTransient而不是@XmlElement对字段进行注释,也会跳过它。

在您的情况下,您需要编写三个类,即Notes,note和parameter。

@XmlRootElement(name="Notes")
public class Notes {
  public List<Note> notes;
}

@XmlRootElement(name="Note")
public class Note {
 public parameter param;
}

@XmlRootElement(name="parameter")
public class parameter {
  public String name; //value of parameter with name notesText
  public Boolean value; //value of parameter with name ispublic
}
相关问题