我相当肯定,这是
XML到
Java对象转换的许多重复的问题之一.
但是我开始了这个线程,因为我找不到更简单的解决方案.
但是我开始了这个线程,因为我找不到更简单的解决方案.
我有一个xsd [我正在设计它]和xml.
我想根据映射将xml数据自动映射到Java bean
<tns:SummaryCart xmlns:tns="SummaryCart" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="SummaryCart.xsd"> <SummaryElement type="test"> <order>1</order> <id>A</id> <displayName>A</displayName> <subElements> <order>1</order> <id>Preactivation</id> <displayName>Preactivation</displayName> </subElements> <maxlines>1</maxlines> </SummaryElement> </tns:SummaryCart>
现在我的Java类将会
public class SummaryCart{ private List<SummaryElement> summaryElementList; } public class SummaryElement { private int order; private String id; private String displayName; private String property; private List<SummaryElement> subElements; private int maxlines; private String type; }
有没有任何简单的工具/框架可以自动将数据从XML映射到Java beans(必须支持属性/元素映射).教程会很好
Btw,我正在使用Spring框架,如果采用spring-oxm优势,欢迎.
下面是如何使用
JAXB (JSR-222)将对象映射到XML.JDK / JRE中包含一个实现,从Java SE 6开始.JSXB由Spring支持(参见第8.5节:
http://static.springsource.org/spring-ws/site/reference/html/oxm.html)
原文链接:https://www.f2er.com/xml/292196.htmlSummaryCart
import java.util.List; import javax.xml.bind.annotation.*; @XmlRootElement(name="SummaryCart",namespace="SummaryCart") @XmlAccessorType(XmlAccessType.FIELD) public class SummaryCart{ @XmlElement(name="SummaryElement") private List<SummaryElement> summaryElementList; }
SummaryElement
import java.util.List; import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) public class SummaryElement { private int order; private String id; private String displayName; private String property; private List<SummaryElement> subElements; private int maxlines; @XmlAttribute private String type; }
演示
import java.io.File; import javax.xml.bind.*; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(SummaryCart.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); File xml = new File("src/forum15881876/input.xml"); SummaryCart sc = (SummaryCart) unmarshaller.unmarshal(xml); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,"SummaryCart.xsd"); marshaller.marshal(sc,System.out); } }
input.xml中/输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <ns2:SummaryCart xmlns:ns2="SummaryCart" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="SummaryCart.xsd"> <SummaryElement type="test"> <order>1</order> <id>A</id> <displayName>A</displayName> <subElements> <order>1</order> <id>Preactivation</id> <displayName>Preactivation</displayName> <maxlines>0</maxlines> </subElements> <maxlines>1</maxlines> </SummaryElement> </ns2:SummaryCart>