jaxb api что это

Java XML API: выбираем правильно. StAX: работаем с удовольствием

в 60% проектов и посвятил ей занятие своей стажировки Masterjava. Наиболее частые его применения: XHTML, SOAP, различные конфигурации (например Tomcat, SoapUI, IntelliJ IDEA, Spring XML конфигурация), импорт-экспорт данных.

В Java есть несколько API для работы с XML и для разработчика важно понимать, какое из API требуется выбрать в каждой конкретной ситуации. В этой статье я кратко перечислю все Java XML API, их назначение и примеры использования, и подробнее остановлюсь на работе с достаточно редкой, но в ряде случаев единственно верной технологией StAX. Предполагается что с элементами XML вы уже знакомы.

Java XML API: выбираем правильно

StAX: работаем с удовольствием

Прежде всего хочу отметить, что со StAX можно работать через 2 API: низкоуровневое XMLStreamReader, возвращающая примитивы и высокоуровневое XMLEventReader, которое возвращает объекты и расходует больше памяти. Далее я буду работать с XMLStreamReader. Сделав над ним обертку работа с XML будет простой и удобной.Разберем небольшой пример: есть простой XML с городами и юзерами:В реальности этот XML может содержать сотни городов и сотни тысяч / миллионы юзеров. Все, что требуется: распечатать список городов. В данном случае StAX API — единственно верный выбор. Добавляем в проект вспомогательный класс StaxStreamProcessor :Далее мы последовательно идем по XML, считываем все интересные нам события и выводим требуемую информацию:Чтобы постоянно не дублировать в программе часто повторяющийся код поиска нужного события в XML, мы можем добавить его в StaxStreamProcessor :Пользоваться утильным классом станет не просто, а очень просто:Недостаток этого кода — мы совершенно бесполезно потратим ресурсы на прохождение по сотням тысяч ненужных нам юзеров вместо завершения программы. Нужно добавить условие прекращение сканирования XML. Обычно это конец тэга родительского элемента (в нашем случае Cities ). Добавляем в StaxStreamProcessor еще один утильный метод, который сканирует XML либо до конца тэга родителя, либо до заданного элемента:Добавим методы чтения атрибута и текста:Код вызова останется суперпростым и мы прекратим обработку XML сразу после конца тега Cities :StAX API требует аккуратность при чтении событий. Если в выводе мы помяняем местами чтение атрибута и текста, но код станет нерабочим: после прочтения из XML названия города атрибут останется позади и будет недоступен. Также следует помнить, что, в зависимости от текущего положения XML, нам доступны одни методы API чтения из XML и недоступны другие.Используя startElement можно добираться до элементов XML любой степени вложенности и, по мере необходимости, дополнять StaxStreamProcessor другими утильными методами. Надеюсь что с данным подходом работа с StAX покажется вам легкой и удобной.

Источник

Technical Article

You will find the following topics covered in this article:

Contents

What’s JAXB?

The Extensible Markup Language (XML) and Java technology are natural partners in helping developers exchange data and programs across the Internet. That’s because XML has emerged as the standard for exchanging data across disparate systems, and Java technology provides a platform for building portable applications. This partnership is particularly important for Web services, which promise users and application developers program functionality on demand from anywhere to anywhere on the Web. XML and Java technology are recognized as ideal building blocks for developing Web services and applications that access Web services.

But how do you couple these partners in practice? More specifically, how do you access and use an XML document (that is, a file containing XML-tagged data) through the Java programming language? One way to do this, perhaps the most typical way, is through parsers that conform to the Simple API for XML (SAX) or the Document Object Model (DOM).

XML and Java technology are recognized as ideal building blocks for developing Web services and applications that access Web services. A new Java API called Java Architecture for XML Binding (JAXB) can make it easier to access XML documents from applications written in the Java programming language.

In the DOM approach, the parser creates a tree of objects that represents the content and organization of data in the document. In this case, the tree exists in memory. The application can then navigate through the tree to access the data it needs, and if appropriate, manipulate it.

Now developers have another Java API at their disposal that can make it easier to access XML documents: Java Architecture for XML Binding (JAXB). A Reference Implementation of the API is now available in the Java Web Services Developer Pack V 1.1.

Let’s look at JAXB in action, and compare it to SAX and DOM-based processing.

An Example: Accessing an XML Document

Suppose you need to develop a Java application that accesses and displays data in XML documents such as books.xml. These documents contain data about books, such as book name, author, description, and ISBN identification number. You could use the SAX or DOM approach to access an XML document and then display the data. For example, suppose you took the SAX approach. In that case, you would need to:

Now let’s look at how you use JAXB to access an XML document such as books.xml and display its data. Using JAXB, you would:

JAXB allows Java developers to access and process XML data without having to know XML or XML processing. For example, there’s no need to create or use a SAX parser or write callback methods.

After unmarshalling, your program can access and display the data in the XML document simply by accessing the data in the Java content objects and then displaying it. There is no need to create and use a parser and no need to write a content handler with callback methods. What this means is that developers can access and process XML data without having to know XML or XML processing.

Bind the Schema

Binding an XML Schema

JAXB simplifies access to an XML document from a Java program by presenting the XML document to the program in a Java format. The first step in this process is to bind the schema for the XML document into a set of Java classes that represents the schema.

Schema: A schema is an XML specification that governs the allowable components of an XML document and the relationships between the components. For example, a schema identifies the elements that can appear in an XML document, in what order they must appear, what attributes they can have, and which elements are subordinate (that is, are child elements) to other elements. An XML document does not have to have a schema, but if it does, it must conform to that schema to be a valid XML document. JAXB requires that the XML document you want to access has a schema, and that schema is written in the W3C XML Schema Language (see the box «Why W3C XML Schema Language?»).

Читайте также:  Что значит сухопарый человек

Why W3C XML Schema Language?

Binding: Binding a schema means generating a set of Java classes that represents the schema. All JAXB implementations provide a tool called a binding compiler to bind a schema (the way the binding compiler is invoked can be implementation-specific). For example, the JAXB Reference Implementation provides a binding compiler that you can invoke through scripts. Suppose, for example, you want to bind the books.xsd schema using the binding compiler provided by the JAXB Reference Implementation. Suppose too that you’re working in the Solaris Operating Environment. Here’s a command you can use to run the script that binds the schema:

In response, the binding compiler generates a set of interfaces and a set of classes that implement the interfaces. Here are the interfaces it generates for the books.xsd schema:

In total, the generated classes represent the entire books.xsd schema. Notice that the classes define get and set methods that are used to respectively obtain and specify data for each type of element and attribute in the schema.

You then compile the generated interfaces and classes. For example:

javac test/jaxb/*.java test/jaxb/impl/*.java

This compiles all of the interfaces and classes in the test.jaxb package generated by the binding compiler.

Unmarshal the Document

Unmarshalling an XML document means creating a tree of content objects that represents the content and organization of the document. The content tree is not a DOM-based tree. In fact, content trees produced through JAXB can be more efficient in terms of memory use than DOM-based trees.

To unmarshal an XML document, you:

After obtaining the data, you can display it directly from your program. Here, for example, is a program that unmarshals the data in the books.xml file and then displays the data. If you run the program, you should see the following result:

Validating the Source Data: Notice that the program includes the following statement:

This statement highlights an important feature of JAXB: you can have it validate the source data against the associated schema as part of the unmarshalling operation. In this case, the statement asks JAXB to validate the source data against its schema. If the data is found to be invalid (that is, it doesn’t conform to the schema) the JAXB implementation can report it and might take further action. JAXB providers have a lot of flexibility here. The JAXB specification mandates that all provider implementations report validation errors when the errors are encountered, but the implementation does not have to stop processing the data. Some provider implementations might stop processing when the first error is found, others might stop even if many errors are found. In other words, it is possible for a JAXB implementation to successfully unmarshal an invalid XML document, and build a Java content tree. However, the result won’t be valid. The main requirement is that all JAXB implementations must be able to unmarshal valid documents.

You can validate source data against an associated schema as part of the unmarshalling operation.

You also have the flexibility of turning the validation switch off if you don’t want to incur the additional validation processing overhead.

Another Example: Building an XML Document

Instead of accessing data in an XML document, suppose you need to build an XML document through a Java application. Here too using JAXB is easier. Let’s investigate.

Unlike the SAX approach, there is no need in DOM to write a content handler and callback methods. However the DOM approach requires you to understand the organization of the document tree. In fact, if you use DOM to access data, you create a parser that builds a tree, and then you use DOM methods to navigate to the appropriate object in the tree that contains the data you need. So an understanding of the tree’s organization is a requirement. Compare this to JAXB, where you have direct access to unmarshalled XML data through objects in the content tree. As in DOM-based processing, JAXB allows access to data in non-sequential order, but it doesn’t force an application to navigate through a tree to access the data. In addition, with all the creating and appending of objects that represent the nodes of the tree, the DOM approach can be tedious.

Here, for example, is a program that uses DOM to build and populate a document, and then write the document to an XML file. Notice that the type of data that gets populated into the document is similar to the data in the books.xml file that was used in the first example, Accessing an XML Document. In fact, the program validates the document it builds against the books.xsd schema that was used in the first example.

Now let’s look at how you use JAXB to build the same document, validate it against the books.xsd schema, and write the document to an XML file. Using JAXB, you would:

As in DOM-based processing, JAXB allows access to data in non-sequential order, but it doesn’t force an application to navigate through a tree to access the data.

In this process, you don’t deal with the intricacies of the DOM object model or even need to know XML.

Bind the Schema

This is the same operation you perform prior to unmarshalling a document. In this case, the schema is for the XML document you want to build. Of course, if you’ve already bound the schema (for instance, you unmarshalled an XML document, updated the data, and now want to write the updated data back to the XML document), you don’t have to bind the schema again.

Читайте также:  распилить кость болгаркой каким диском

Create the Content Tree

The content tree represents the content that you want to build into the XML document. You can create the content tree by unmarshalling XML data, or you can create it using the ObjectFactory class that’s generated by binding the appropriate schema. Let’s use the ObjectFactory approach. First, create an instance of the ObjectFactory class:

ObjectFactory objFactory = new ObjectFactory();

Next, use create methods in the ObjectFactory object to create each of the objects in the content tree. For example:

Then use set methods in the created objects to specify data values. For example:

Marshal the Content Tree

Marshalling is the opposite of unmarshalling. It creates an XML document from a content tree. To marshal a content tree, you:

Here, for example, is a program that creates a content tree, fills it with data, and then marshals the content tree to an XML file.

Validating the Content Tree: Notice that validation is not performed as part of the marshalling operation. In other words, unlike the case for unmarshalling, there is no setValidating method for marshalling. Instead, when marshalling data, you use the Validator class that is a part of the binding framework to validate a content tree against a schema. For example:

A Final Example: Updating an XML Document

Here’s a final example, one that logically combines elements of accessing an XML document and building an XML document. Suppose you need to update an XML document. In the DOM approach, you would create and use a DOM parser to navigate to the appropriate object in the tree that contains the data you need, update the data, and then write the updated data to an XML file. Here, for example, is a program that uses DOM to update an XML document. As discussed in Building an XML Document, the DOM approach is relatively tedious and forces you to know the organization of the content tree.

Here, by comparison, is a JAXB program that updates an XML document. Specifically, it updates an unmarshalled content tree and then marshals it back to an XML document. Notice how JAXB simplifies the process. The program has direct access to the object it needs to update. The program uses a get method to access the data it needs, and a set method to update the data.

Although it’s tempting to think that the XML data can make a «roundtrip» unchanged, there’s no guarantee of that. In other words, if you use JAXB to unmarshal an XML document and then marshal it back to the same XML file, there’s no guarantee that the XML document will look exactly the same at it did originally. For example, the indentation of the resulting XML document might be a bit different than the original. The JAXB specification does not require the preservation of the XML information set in a roundtrip from XML document-to-Java representation-to XML document. But it also doesn’t forbid the preserving of it.

Binding Can Be Customized

The JAXB specification describes the default behavior for binding a subset of XML schema components to Java components. However JAXB allows you to annotate a schema with binding declarations that override or extend the default binding behavior.

Let’s look at a customization example. Here is an annotated version of the books.xsd schema that was used in the previous examples. The annotations in this example are inline.

Notice the annotation element near the top of the schema:

All binding declarations are in an annotation element and its subordinate appinfo element. In fact, all inline binding declarations must be made this way.

This block of code demonstrates a number of customizations that you can make to a schema:

Make global customizations: The element specifies binding declarations that have global scope. In JAXB, binding declarations can be specified at different levels, or «scopes.» Each scope inherits from the scopes above it, and binding declarations in a scope override binding declarations in scopes above it. Global scope is at the top of the scope hierarchy. It covers all the schema elements in the source schema and (recursively) any schemas that are included or imported by the source schema. Global scope is followed in the hierarchy by Schema scope (covers all the schema elements in the target namespace of a schema), Definition scope (covers all schema elements that reference a specified type definition or a global declaration), and Component scope (applies only to a specific schema element that was annotated with a binding declaration).

Notice that the namespace prefix ( jaxb ) for the element is bound to http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/jaxb/index.html. This URI contains the core schema for binding declarations.

Add method signatures. The declaration generateIsSetMethod=»true» tells the binding compiler to generate isSet methods for the properties of all generated classes. These methods are used to determine if a property in a class is set or has a default value.

As result of the global declarations made earlier, the binding compiler will generate the following methods for the elements tagged as choice :

Additional customizations: Other annotations in the schema illustrate additional types of customization, such as annotating a specific schema element to a Java Content Interface or Java Element Interface. This is done through a binding declaration. In the annotated schema example, a binding declaration is used to specify the name MyCollection for the interface bound to the class. Another binding declaration in the annotated schema example binds the element to its Java representation as a typesafe enumeration class. Although not illustrated in the annotated schema, another type of customization you can make is to specify javadoc for a generated package or class. These are only some of the many binding customizations that JAXB allows.

After you run the program, examine the interfaces and classes that the binding compiler generates, and compare them to the interfaces and classes generated from the uncustomized schema. For example, here is the CollectionType.java file generated for the unnamed complex type for the element. Notice the additional methods that have been added because of the binding customizations.

Читайте также:  какой клапан больше впускной или выпускной на ваз

Distinct Advantages

Let’s reiterate a number of important advantages of using JAXB:

Java developers should find JAXB a welcome aid in developing Web services and other Java-XML applications.

Run the Examples

If you’d like to run the examples in this article with Java Web Services Developer Pack V 1.1, you need to:

setenv JWSDP_HOME install_dir

replace install_dir with the Java Web Services Developer Pack V 1.1 installation directory.

Источник

Руководство по JAXB

Это вводная статья о JAXB (архитектура Java для привязки XML).

1. введение

Это вводная статья о JAXB (архитектура Java для привязки XML).

Сначала мы покажем, как конвертировать объекты Java в XML и наоборот, а затем сосредоточимся на создании классов Java из XML-схемы и наоборот с помощью плагина JAXB-2 Maven.

2. Обзор

JAXB предоставляет быстрый и удобный способ маршалирования (записи) объектов Java в XML и разбиения (чтения) XML на объекты. Он поддерживает структуру привязки, которая сопоставляет XML-элементы и атрибуты с полями и свойствами Java с помощью аннотаций Java.

3. Аннотации JAXB

JAXB использует аннотации Java для дополнения созданных классов дополнительной информацией. Добавление таких аннотаций в существующие классы Java подготавливает их к среде выполнения JAXB.

Давайте сначала создадим простой объект Java, чтобы проиллюстрировать сортировку и отмену сортировки:

Приведенный выше класс содержит следующие аннотации:

Для получения более подробной информации об аннотации JAXB вы можете ознакомиться со следующей ссылкой |.

4. Сортировка – Преобразование объекта Java в XML

Маршаллинг предоставляет клиентскому приложению возможность преобразования дерева объектов Java, производного от JAXB, в данные XML. По умолчанию Маршаллер использует кодировку UTF-8 при создании XML-данных. Далее мы сгенерируем XML-файлы из объектов Java.

javax.xml.привязка.Класс JAXBContext предоставляет точку входа клиента в API JAXB. По умолчанию JAXB не форматирует XML-документ. Это экономит место и предотвращает случайную интерпретацию любого пробела как значительного.

Когда мы запускаем приведенный выше код, мы можем проверить результат в book.xml чтобы убедиться, что мы успешно преобразуем объект Java в данные XML:

5. Отмена сортировки – Преобразование XML в объект Java

Несинхронизация предоставляет клиентскому приложению возможность преобразования XML – данных в объекты Java, полученные из JAXB.

Давайте использовать JAXB Унмаршаллер чтобы унмаршал наш book.xml вернуться к объекту Java:

Когда мы запускаем приведенный выше код, мы можем проверить вывод консоли, чтобы убедиться, что мы успешно преобразовали XML-данные в объект Java:

6. Сложные Типы Данных

При обработке сложных типов данных, которые могут быть недоступны непосредственно в JAXB, мы можем написать адаптер, чтобы указать JAXB, как управлять определенным типом.

Давайте создадим адаптер для указания формата даты при маршалинге:

Давайте применим Адаптер данных к нашей Книге :

Когда мы запускаем приведенный выше код, мы можем проверить результат в book.xml чтобы убедиться, что мы успешно преобразовали наш объект Java в XML с использованием нового формата даты ” гггг-ММ-дд ЧЧ:мм:сс “:

7. Плагин JAXB-2 Maven

Этот плагин использует Java API для привязки XML (JAXB), версия 2+, для создания классов Java из XML-схем (и, возможно, файлов привязки) или для создания XML-схемы из аннотированного класса Java.

7.1. Создание класса Java из XSD

Плагин JAXB-2 Maven использует поставляемый JDK инструмент XJC, инструмент компилятора привязки JAXB, который генерирует классы Java из XSD (определение схемы XML).

Давайте создадим простой файл user.xsd и используем плагин JAXB-2 Maven для создания классов Java из этой схемы XSD:

Давайте настроим плагин Maven JAXB-2:

Мы также можем настроить глобальную привязку JAXB, которая переопределяет правила привязки по умолчанию:

global.xjb выше переопределяет тип DateTime для java.util.Календарь тип.
Когда мы создаем проект, он генерирует файлы классов в папке src/main/java
и пакете com.baeldung.jaxb.gen
.

7.2. Создание схемы XSD из Java

Мы повторно используем файлы классов Java из предыдущего примера. Давайте настроим плагин:

По умолчанию JAXB рекурсивно сканирует все папки в src/main/java на наличие аннотированных классов JAXB. Мы можем указать другую папку source для ваших аннотированных классов JAXB, добавив элемент source в конфигурацию плагина.

8. Заключение

Источник

Использование Java JAXB на примерах

В этом уроке покажу как использовать библиотеку JAXB для работы с XML. На примерах рассмотрим как объекты Java записываются в файлы XML, а данные XML считываются в объекты.

Java Architecture for XML Binding (JAXB) – это программная структура, которая позволяет разработчикам отображать классы Java в представления XML. JAXB позволяет делать сохранение объекта в файл и обратно в объекты.

В Java 9 JAXB переместился в отдельный модуль java.xml. В Java 9 и Java 10 нам нужно использовать параметр –add-modules = java.xml.bind. В Java 11 JAXB был удален из JDK, и нам нужно добавить его в проект в виде отдельной библиотеки через Maven или Gradle.

В наших примерах мы используем JDK 11 и Maven для создания наших приложений.

Определение JAXB – что это?

Маршалинг – это процесс преобразования объектов Java в документы XML. Unmarshalling – это процесс чтения документов XML в объекты Java. Класс JAXBContext обеспечивает точку входа клиента в API JAXB. Он предоставляет API для маршалинга, демаршалинга(unmarshal) и проверки.

Следующий файл POM содержит необходимые JAR JAXB настройки.

В дополнение к включению зависимостей JAXB мы используем плагин maven-assembly-plugin, чтобы упаковать все зависимости в один JAR-файл.

Пример использования JAXB для записи XML

В первом примере мы записываем объекты Java в файл XML.

Этот bean-компонент будет преобразован в определенный тег XML.

С помощью аннотации @XmlRootElement мы определяем имя тега XML.

С помощью атрибута propOrder @ XmlType мы определяем порядок подэлементов.

@XmlElement(name = «title»)
public String getName() <
return name;
>

Мы можем изменить имя элемента по умолчанию на заголовок.

BookStore – это класс, который содержит список, в который мы помещаем наши объекты книги.

@XmlRootElement(namespace = «com.zetcode»)
public class BookStore <
Мы определяем корневой элемент с помощью аннотации @XmlRootElement.

// XmLElementWrapper генерирует элемент-оболочку вокруг представления XML
@XmlElementWrapper(name = «bookList»)
// XmlElement устанавливает имя
@XmlElement(name = «book»)
private ArrayList bookList;

Аннотация @XmlElementWrapper определяет элемент-обертку вокруг элементов книги. Аннотация @XmlElement определяет имя элемента XML, который находится внутри оболочки.

Пример чтения XML JAXB (unmarshal)

Во втором примере мы считываем данные обратно в объекты Java.

Средняя оценка / 5. Количество голосов:

Или поделись статьей

Видим, что вы не нашли ответ на свой вопрос.

Источник

Сказочный портал