将xml字符串转换为Java对象
发布时间:2020-12-16 07:47:41 所属栏目:百科 来源:网络整理
导读:我有以下xml字符串.我想将其转换为 java对象,以使用该对象的字段映射每个标记.如果我可以引入与标记名称相比的不同字段名称,那就更好了.我怎么能这样做?我正在寻找JAXB,但我仍然对“ns4:response”和标签内的标签等部分感到困惑.先感谢您… ns4:response c
我有以下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>
JAXB是Java标准(
JSR-222),用于将对象转换为XML或从XML转换对象.以下应该有所帮助:
从字符串中解组 在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); 不同的字段和XML名称 您可以使用@XmlElement批注指定您希望元素名称的内容.默认情况下,JAXB会查看属性.如果您希望将映射基于字段,则需要设置@XmlAccessorType(XmlAccessType.FIELD). @XmlElement(name="count") private int size; 命名空间 @XmlRootElement和@XmlElement注释还允许您在需要时指定命名空间限定. @XmlRootElement(namespace="http://www.example.com") public class Response { } 欲获得更多信息 > http://blog.bdoughan.com/2010/08/jaxb-namespaces.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |