ITeye博客

使用jaxb将XML转化为JAVA BEAN

awdxzc · 2011-04-15 11:41 · Common · 编程语言 · Java · .net · XML · Bean · Markdown

直接贴代码了,其中的参数的意思,自己查查就知道了,或者用一下就明白了。 [code="java"] import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; @XmlRootElement(name="module") public class Module extends Metadata{ @XmlAttribute(name="name") public String name; @XmlAttribute(name="template") public String template; @XmlElement public Resources resources; @XmlElement public HeaderItems headerItems; @XmlElement public Properties properties; @XmlElement public BodyItems bodyItems; @XmlTransient public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlTransient public String getTemplate() { return template; } public void setTemplate(String template) { this.template = template; } @XmlTransient public Resources getResources() { return resources; } public void setResources(Resources resources) { this.resources = resources; } @XmlTransient public HeaderItems getHeaderItems() { return headerItems; } public void setHeaderItems(HeaderItems headerItems) { this.headerItems = headerItems; } @XmlTransient public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } @XmlTransient public BodyItems getBodyItems() { return bodyItems; } public void setBodyItems(BodyItems bodyItems) { this.bodyItems = bodyItems; } } [/code] Moduel对象其中一个对象属性: [code="java"] import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient; public class HeaderItems extends Metadata { @XmlElement(name="field") private List fields; @XmlTransient public List getFields() { return fields; } public void setFields(List fields) { this.fields = fields; for (int i=0; i getEntriesList() { return entries.getEntryList(); } } [/code] 最后XML闪亮登场: [code="java"] [/code] Metadata是一个抽象类,描述了些 ID NAME VALUE基本属性 没什么特别的 关于XML转java对象的操作: [code="java"] public static Module parse(String metadata) throws MetadataParserException { Module module = null; try { JAXBContext jaxbContext = JAXBContext.newInstance(Module.class); Unmarshaller um = jaxbContext.createUnmarshaller(); module = (Module)um.unmarshal(new ByteArrayInputStream(metadata.getBytes())); } catch (JAXBException e) { log.warn("JAXB castor failed to convert the metadata to module instance by {}",e.getMessage()); throw new MetadataParserException(); } return module; } [/code] 这样的话传进XML的字符串,就可以解析出这个JAVA对象。完全不用写任何过多的代码。岂不爽哉?!!!! 附一个java bean <=> xml 的unmi同志原创文档,主要是比较Jaxb和castor。 [b][color=red]提供一个JAXB学习的地址:[url]http://jaxb.java.net/[/url][/color][/b]

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。