ghT*_*ath 7 java xml string jaxb
我有以下xml字符串.我想将其转换为java对象,以使用该对象的字段映射每个标记.如果我可以引入与标记名称相比的不同字段名称,那就更好了.我怎么能这样做?我正在寻找JAXB,但我仍然对"ns4:response"和标签内的标签等部分感到困惑.先感谢您...
<ns4:response>
<count>1</count>
<limit>1</limit>
<offset>1</offset>
<ns3:payload xsi:type="productsPayload">
<products>
<product>
<avgRating xsi:nil="true"/>
<brand>Candie's</brand>
<description>
<longDescription>
long descriptions
</longDescription>
<shortDescription>
short description
</shortDescription>
</description>
<images>
<image>
<altText>alternate text</altText>
<height>180.0</height>
<url>
url
</url>
<width>180.0</width>
</image>
</images>
<price>
<clearancePrice xsi:nil="true"/>
<regularPrice xsi:nil="true"/>
<salePrice>28.0</salePrice>
</price>
</product>
</products>
</ns3:payload>
</ns4:response>
Run Code Online (Sandbox Code Playgroud)
bdo*_*han 20
JAXB是用于将对象转换为XML或从XML转换对象的Java标准(JSR-222).以下应该有所帮助:
从字符串中解组
在JAXB impl可以解String组StringReader之前,您需要将实例包装起来.
StringReader sr = new StringReader(xmlString);
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Response response = (Response) unmarshaller.unmarshal(sr);
Run Code Online (Sandbox Code Playgroud)
不同的字段和XML名称
您可以使用@XmlElement注释指定您希望元素名称的内容.默认情况下,JAXB会查看属性.如果您希望将字母映射到字段上,则需要进行设置@XmlAccessorType(XmlAccessType.FIELD).
@XmlElement(name="count")
private int size;
Run Code Online (Sandbox Code Playgroud)
命名空间
该@XmlRootElement和@XmlElement注解也让你在需要的地方指定的命名空间的资格.
@XmlRootElement(namespace="http://www.example.com")
public class Response {
}
Run Code Online (Sandbox Code Playgroud)
欲获得更多信息