我要在Java对象中解析以下xml:
<ArrayOfTranslateArrayResponse xmlns="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<TranslateArrayResponse>
<From>it</From>
<OriginalTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:int>5</a:int>
</OriginalTextSentenceLengths>
<TranslatedText>Mom</TranslatedText>
<TranslatedTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:int>3</a:int>
</TranslatedTextSentenceLengths>
</TranslateArrayResponse>
<TranslateArrayResponse>
<From>it</From>
<OriginalTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:int>4</a:int>
</OriginalTextSentenceLengths>
<TranslatedText>Dad</TranslatedText>
<TranslatedTextSentenceLengths xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:int>3</a:int>
</TranslatedTextSentenceLengths>
</TranslateArrayResponse>
这是我实施的两个课程:
@XmlRootElement(name="ArrayOfTranslateArrayResponse")
@XmlAccessorType(XmlAccessType.FIELD)
@Getter
@Setter
@ToString
public class TranslateResponse {
@XmlElement(name="TranslateArrayResponse")
private LinkedList<TranslatedResponseObject> translations;
}
和
@XmlAccessorType(XmlAccessType.FIELD)
@Getter
@Setter
@ToString
public class TranslatedResponseObject {
@XmlElement(name="TranslatedText")
private String translatedText;
}
通过提供xml示例的unmarshall,我收到了字段翻译的null。有什么问题?
答案 0 :(得分:1)
我已经得到了解决方案,感谢@klonq建议调试问题。必须以这种方式在每个@XmlElement和@XmlRootElement上添加命名空间:
@XmlRootElement(name="ArrayOfTranslateArrayResponse", namespace="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2")
@XmlAccessorType(XmlAccessType.FIELD)
@Getter
@Setter
@ToString
public class TranslateResponse {
@XmlElement(name="TranslateArrayResponse", namespace="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2")
private LinkedList<TranslatedResponseObject> translations;
}
@XmlAccessorType(XmlAccessType.FIELD)
@Getter
@Setter
@ToString
public class TranslatedResponseObject {
@XmlElement(name="TranslatedText", namespace="http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2")
private String translatedText;
}
答案 1 :(得分:0)
您可以使用ValidationEventHandler来调试问题。
public class MyValidationEventHandler implements ValidationEventHandler {
@Override
public boolean handleEvent(ValidationEvent event) {
switch (event.getSeverity()) {
case ValidationEvent.WARNING:
case ValidationEvent.ERROR:
case ValidationEvent.FATAL_ERROR: {
log.error("Validation event : {} in {} line {} col {}",
event.getMessage(),
event.getLocator().getURL(),
event.getLocator().getLineNumber(),
event.getLocator().getColumnNumber());
return false;
}
default:
return true;
}
}
}
你使用它如下:
final JAXBContext jAXBContext = JAXBContext.newInstance(target);
final Unmarshaller unmarshaller = jAXBContext.createUnmarshaller();
unmarshaller.setEventHandler(new MyValidationEventHandler());
unmarshaller.unmarshal(file);