Вы можете сделать это с JAXB следующим образом:
@XmlRootElement(name = "Test")
class Policy {
private Message message;
public Message getMessage() {
return this.message;
}
public void setMessage(Message message) {
this.message = message;
}
@Override
public String toString() {
return "Policy [message=" + this.message + "]";
}
}
public class Message {
private int num;
private List<Object> content;
@XmlAttribute
public int getNum() {
return this.num;
}
public void setNum(int num) {
this.num = num;
}
@XmlMixed
@XmlElementRefs({
@XmlElementRef(name="care", type=Care.class)})
public List<Object> getContent() {
return this.content;
}
public void setContent(List<Object> content) {
this.content = content;
}
@XmlTransient
public String getText() {
if (this.content == null)
return null;
StringBuilder text = new StringBuilder();
for (Object obj : this.content)
if (obj instanceof String)
text.append(obj);
return text.toString().trim();
}
@XmlTransient
public List<String> getCare() {
if (this.content == null)
return null;
List<String> care = new ArrayList<>();
for (Object obj : this.content)
if (obj instanceof Care)
care.add(((Care) obj).getValue());
return care;
}
@Override
public String toString() {
return "Message[num=" + this.num + ", content=" + this.content + "]";
}
}
@XmlRootElement(name = "care")
public class Care {
private String value;
@XmlValue
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public String toString() {
return "Care[value=" + this.value + "]";
}
}
Тест
String input = "<Test>\r\n" +
" <message num=\"90\">[WANT TO EXTRACT THIS DATA]\r\n" +
" <care>test data 1</care>\r\n" +
" <care>test data 2</care>\r\n" +
" </message>\r\n" +
"</Test>";
JAXBContext jaxbContext = JAXBContext.newInstance(Policy.class, Care.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Policy policy = (Policy) unmarshaller.unmarshal(new StringReader(input));
System.out.println(policy);
System.out.println("text = \"" + policy.getMessage().getText().replace("\n", "\\n") + "\"");
System.out.println("care = " + policy.getMessage().getCare());
Выход
Policy [message=Message[num=90, content=[[WANT TO EXTRACT THIS DATA]
, Care[value=test data 1],
, Care[value=test data 2],
]]]
text = "[WANT TO EXTRACT THIS DATA]"
care = [test data 1, test data 2]