Как генерировать классы JAXB из XSD?
Я полный новичок в XML. Я делаю реализацию REST проекта Java EE, и мы возвращаем много XML. С этим мы решили использовать JAXB. До сих пор мы вручную кодировали модели для XML.
Но уже существуют такие сложные структуры, которые мы не умеем кодировать. Мы читали о создании классов из XSD. У нас есть XSD.
Мои вопросы:
1.) Я читал о XJC, где я могу его найти?
2.) Мы должны установить весь JAXB? (ну и что мы используется до сих пор? разве это не ДЖАКСБ?)
11 ответов:
XJC включен в каталог bin в JDK, начиная с Java SE 6. Пример см.:
Содержание блога выглядит следующим образом:Обработка потоков атомов с помощью JAXB Atom-это формат XML для представления веб-каналов. Стандартный формат позволяет приложениям для чтения отображать каналы из разных источников. В этом примере мы будем обрабатывать Atom feed для этого блога.
Демо
В этом примере мы будем использовать JAXB для преобразования XML-канала Atom, соответствующего этому блогу, в объекты, а затем обратно в XML.
import java.io.InputStream; import java.net.URL; import javax.xml.bind.*; import javax.xml.transform.stream.StreamSource; import org.w3._2005.atom.FeedType; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance("org.w3._2005.atom"); Unmarshaller unmarshaller = jc.createUnmarshaller(); URL url = new URL("http://bdoughan.blogspot.com/atom.xml"); InputStream xml = url.openStream(); JAXBElement<feedtype> feed = unmarshaller.unmarshal(new StreamSource(xml), FeedType.class); xml.close(); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(feed, System.out); } }Модель JAXB
Следующая модель была сгенерирована компилятором schema to Java (XJC). Я опустил методы get / set и комментарии, чтобы сэкономить место.
xjc -d generated http://www.kbcafe.com/rss/atom.xsd.xmlPackage-info
@XmlSchema( namespace = "http://www.w3.org/2005/Atom", elementFormDefault = XmlNsForm.QUALIFIED) @XmlAccessorType(XmlAccessType.FIELD) package org.w3._2005.atom; import javax.xml.bind.annotation.*;CategoryType
package org.w3._2005.atom; import java.util.*; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.*; import javax.xml.namespace.QName; @XmlType(name = "categoryType") public class CategoryType { @XmlAttribute(required = true) protected String term; @XmlAttribute @XmlSchemaType(name = "anyURI") protected String scheme; @XmlAttribute protected String label; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); }Содержание Тип
package org.w3._2005.atom; import java.util.*; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.*; import javax.xml.namespace.QName; @XmlType(name = "contentType", propOrder = {"content"}) public class ContentType { @XmlMixed @XmlAnyElement(lax = true) protected List<Object> content; @XmlAttribute protected String type; @XmlAttribute @XmlSchemaType(name = "anyURI") protected String src; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); }DateTimeType
package org.w3._2005.atom; import java.util.*; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.*; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; @XmlType(name = "dateTimeType", propOrder = {"value"}) public class DateTimeType { @XmlValue @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar value; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); }EntryType
package org.w3._2005.atom; import java.util.*; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.*; import javax.xml.namespace.QName; @XmlType(name = "entryType", propOrder = {"authorOrCategoryOrContent"}) public class EntryType { @XmlElementRefs({ @XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "summary", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "source", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "content", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "published", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class) }) @XmlAnyElement(lax = true) protected List<Object> authorOrCategoryOrContent; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); }FeedType
package org.w3._2005.atom; import java.util.*; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.*; import javax.xml.namespace.QName; @XmlType(name = "feedType", propOrder = {"authorOrCategoryOrContributor"}) public class FeedType { @XmlElementRefs({ @XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "generator", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "icon", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "subtitle", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "entry", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "logo", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class) }) @XmlAnyElement(lax = true) protected List<Object> authorOrCategoryOrContributor; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); }GeneratorType
package org.w3._2005.atom; import java.util.*; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.*; import javax.xml.namespace.QName; @XmlType(name = "generatorType", propOrder = {"value"}) public class GeneratorType { @XmlValue protected String value; @XmlAttribute @XmlSchemaType(name = "anyURI") protected String uri; @XmlAttribute protected String version; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); }IconType
package org.w3._2005.atom; import java.util.*; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.*; import javax.xml.namespace.QName; @XmlType(name = "iconType", propOrder = {"value"}) public class IconType { @XmlValue @XmlSchemaType(name = "anyURI") protected String value; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); }IdType
package org.w3._2005.atom; import java.util.*; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.*; import javax.xml.namespace.QName; @XmlType(name = "idType", propOrder = {"value"}) public class IdType { @XmlValue @XmlSchemaType(name = "anyURI") protected String value; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); }LinkType
package org.w3._2005.atom; import java.math.BigInteger; import java.util.*; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.*; import javax.xml.namespace.QName; @XmlType(name = "linkType", propOrder = {"content"}) public class LinkType { @XmlValue protected String content; @XmlAttribute(required = true) @XmlSchemaType(name = "anyURI") protected String href; @XmlAttribute protected String rel; @XmlAttribute protected String type; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NMTOKEN") protected String hreflang; @XmlAttribute protected String title; @XmlAttribute @XmlSchemaType(name = "positiveInteger") protected BigInteger length; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); }Логотип
package org.w3._2005.atom; import java.util.*; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.*; import javax.xml.namespace.QName; @XmlType(name = "logoType", propOrder = {"value"}) public class LogoType { @XmlValue @XmlSchemaType(name = "anyURI") protected String value; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); }PersonType
package org.w3._2005.atom; import java.util.*; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.*; import javax.xml.namespace.QName; @XmlType(name = "personType", propOrder = {"nameOrUriOrEmail"}) public class PersonType { @XmlElementRefs({ @XmlElementRef(name = "email", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "name", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "uri", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class) }) @XmlAnyElement(lax = true) protected List<Object> nameOrUriOrEmail; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); }SourceType
package org.w3._2005.atom; import java.util.*; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.*; import javax.xml.namespace.QName; @XmlType(name = "sourceType", propOrder = {"authorOrCategoryOrContributor"}) public class SourceType { @XmlElementRefs({ @XmlElementRef(name = "updated", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "category", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "subtitle", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "logo", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "generator", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "icon", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "title", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "id", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "author", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "contributor", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "link", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class), @XmlElementRef(name = "rights", namespace = "http://www.w3.org/2005/Atom", type = JAXBElement.class) }) @XmlAnyElement(lax = true) protected List<Object> authorOrCategoryOrContributor; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); }TextType
package org.w3._2005.atom; import java.util.*; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.*; import javax.xml.namespace.QName; @XmlType(name = "textType", propOrder = {"content"}) public class TextType { @XmlMixed @XmlAnyElement(lax = true) protected List<Object> content; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String type; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); }UriType
package org.w3._2005.atom; import java.util.*; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.*; import javax.xml.namespace.QName; @XmlType(name = "uriType", propOrder = {"value"}) public class UriType { @XmlValue @XmlSchemaType(name = "anyURI") protected String value; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anyURI") protected String base; @XmlAttribute(namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "language") protected String lang; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); }
Для Eclipse STS (3.5 по крайней мере) вам не нужно ничего устанавливать. щелкните правой кнопкой мыши на схеме.классы xsd -> Generate -> JAXB. вам нужно будет указать пакет и местоположение на следующем шаге, и это все, ваши классы должны быть сгенерированы. Я предполагаю, что все вышеперечисленные решения работают, но это кажется намного проще (для пользователей STS).
[UPDATE] Eclipse STS версии 3.6 (на основе Kepler) поставляется с той же функциональностью.
1) Вы можете использовать стандартную утилиту Java хотя XJC - ([Ваш домашний каталог Java]\бин\хотя XJC.исполняемый). Но вам нужно творить .bat (или .sh) скрипт для его использования.
Например, генерировать.летучая мышь:
[your java home dir]\bin\xjc.exe %1 %2 %3Например, тест-схема.xsd:
<?xml version="1.0"?> <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" targetNamespace="http://myprojects.net/xsd/TestScheme" xmlns="http://myprojects.net/xsd/TestScheme"> <xs:element name="employee" type="PersonInfoType"/> <xs:complexType name="PersonInfoType"> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:schema>Беги .bat-файл с параметрами: generate.летучая мышь тест-схема.xsd-d [ваш src dir]
Для получения дополнительной информации используйте эту документацию - http://docs.oracle.com/javaee/5/tutorial/doc/bnazg.html
И это - http://docs.oracle.com/javase/6/docs/technotes/tools/share/xjc.html
2) JAXB (утилита xjc) по умолчанию устанавливается вместе с JDK6.
Cxf делает большую поддержку для такого рода вещей, например
<plugin> <groupId>org.apache.cxf</groupId> <artifactId>cxf-xjc-plugin</artifactId> <version>2.3.0</version> <configuration> <extensions> <extension>org.apache.cxf.xjcplugins:cxf-xjc-dv:2.3.0</extension> </extensions> </configuration> <executions> <execution> <id>generate-sources-trans</id> <phase>generate-sources</phase> <goals> <goal>xsdtojava</goal> </goals> <configuration> <sourceRoot>${basedir}/src/main/java</sourceRoot> <xsdOptions> <xsdOption> <xsd>src/main/resources/xxx.xsd</xsd> </xsdOption> </xsdOptions> </configuration> </execution> </executions> </plugin>
Если вы используете Eclipse, вы также можете попробовать JAXB Eclipse Plug-In
Вы можете найти дополнительную информацию о компиляторе привязки XJC, который поставляется с установкой jdk здесь: xjc: Java™ Architecture for XML Binding-компилятор привязки
Надеюсь, это поможет!
- Скачать http://java.net/downloads/jaxb-workshop/IDE%20plugins/org.jvnet.jaxbw.zip
- извлеките zip-файл .
- Поместите организацию.спнет.джаксбв.eclipse_1.0.В папку 0 .папка eclipse\plugins
- перезапустить затмение.
- Щелкните правой кнопкой мыши на xsd-файле,и вы найдете меню contect. JAXB 2.0 - > выполнить XJC .
В intellij нажмите .XSD-файл - >Веб-сервисы - >Генерировать Java-код из Xml-схемы JAXB затем укажите путь к пакету и имя пакета - >ok
В
Eclipseщелкните правой кнопкой мыши на файлеxsd, который вы хотите получить --> Generate --> Java... -- >Генератор: "схема к классам Java JAXB".Я только что столкнулся с той же проблемой, у меня была куча
xsdфайлов, только один из них былXML Root Element, и он хорошо работал, что я объяснил выше в Eclipse
Вы также можете генерировать исходный код из схемы, используя jaxb2-maven-plugin plugin:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jaxb2-maven-plugin</artifactId> <version>2.2</version> <executions> <execution> <goals> <goal>xjc</goal> </goals> </execution> </executions> <configuration> <sources> <source>src/main/resources/your_schema.xsd</source> </sources> <xjbSources> <xjbSource>src/main/resources/bindings.xjb</xjbSource> </xjbSources> <packageName>some_package</packageName> <outputDirectory>src/main/java</outputDirectory> <clearOutputDir>false</clearOutputDir> <generateEpisode>false</generateEpisode> <noGeneratedHeaderComments>true</noGeneratedHeaderComments> </configuration> </plugin>
Вы можете скачать файлы JAXB jar из http://jaxb.java.net/2.2.5/ Вам не нужно ничего устанавливать, просто вызовите команду xjc и с аргументом classpath, указывающим на загруженные файлы JAXB jar.
Вы можете увидеть мой вопрос здесь Как выполнить компилятор JAXB из ANT имеет ответ пример использования ant.

Comments