DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How To Get the Comments From a DOCX Document in Java
  • Extracting Data From Very Large XML Files With X-definition
  • Google Cloud Document AI Basics
  • Thumbnail Generator Microservice for PDF in Spring Boot

Trending

  • AI, ML, and Data Science: Shaping the Future of Automation
  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • Failure Handling Mechanisms in Microservices and Their Importance
  • Rust and WebAssembly: Unlocking High-Performance Web Apps
  1. DZone
  2. Coding
  3. Languages
  4. Handle the Middle of a XML Document with JAXB and StAX

Handle the Middle of a XML Document with JAXB and StAX

By 
Blaise Doughan user avatar
Blaise Doughan
·
Aug. 27, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
18.4K Views

Join the DZone community and get the full member experience.

Join For Free
Recently I have come across a lot of people asking how to read data from, or write data to the middle of an XML document.  In this post I will demonstrate how this can be done using JAXB with StAX.  Note:  JAXB (JSR-222) and StAX (JSR-173) implementations are included in the JDK/JRE since Java SE 6.

XML (input.xml)

We will be using a SOAP message as our sample XML.  The outer portions of the XML document represent information relevant to the Web Service and the inner portions (lines 5-8) represent the data we want to convert to our domain model.
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns0:findCustomerResponse xmlns:ns0="http://service.jaxws.blog/">
            <return id="123">
                <firstName>Jane</firstName>
                <lastName>Doe</lastName>
            </return>
        </ns0:findCustomerResponse>
    </S:Body>
</S:Envelope>

Java Model 

Our Java model consists of a single domain class.  The concepts in this example also apply to larger domain models.
package blog.stax.middle;
 
import javax.xml.bind.annotation.*;
 
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
 
    @XmlAttribute
    int id;
     
    String firstName;
     
    String lastName;
     
}
Unmarshal Demo

To unmarshal from the middle of an XML document all we need to do is the following:
  1. Create an XMLStreamReader from the XML input (line 12).
  2. Advance the XMLStreamReader to the return element (lines 13-16).
  3. Unmarshal an instance of Customer from the XMLStreamReader (line 20)
    package blog.stax.middle;
     
    import javax.xml.bind.*;
    import javax.xml.stream.*;
    import javax.xml.transform.stream.StreamSource;
     
    public class UnmarshalDemo {
     
        public static void main(String[] args) throws Exception {
            XMLInputFactory xif = XMLInputFactory.newFactory();
            StreamSource xml = new StreamSource("src/blog/stax/middle/input.xml");
            XMLStreamReader xsr = xif.createXMLStreamReader(xml);
            xsr.nextTag();
            while(!xsr.getLocalName().equals("return")) {
                xsr.nextTag();
            }
     
            JAXBContext jc = JAXBContext.newInstance(Customer.class);
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            JAXBElement<Customer> jb = unmarshaller.unmarshal(xsr, Customer.class);
            xsr.close();
     
            Customer customer = jb.getValue();
            System.out.println(customer.id);
            System.out.println(customer.firstName);
            System.out.println(customer.lastName);
        }
     
    }
 
Output 

Below is the output from running the unmarshal demo.
123
Jane
Doe

Marshal Demo

To marshal to the middle of an XML document all we need to do is the following:
  1. Create an XMLStreamWriter for the XML output (line 18).
  2. Start the document and write the outer elements (lines 19-22).
  3. Set the Marshaller.JAXB_FRAGMENT property on the Marshaller (line 26) to prevent the XML declaration from being written.
  4. Marshal an instance of Customer to the XMLStreamWriter (line 27).
  5. End the document, this will close any elements that have been opened (line 29).
    package blog.stax.middle;
     
    import javax.xml.bind.*;
    import javax.xml.namespace.QName;
    import javax.xml.stream.*;
     
    public class MarshalDemo {
     
        public static void main(String[] args) throws Exception {
            Customer customer = new Customer();
            customer.id = 123;
            customer.firstName = "Jane";
            customer.lastName = "Doe";
            QName root = new QName("response");
            JAXBElement<Customer> je = new JAXBElement<Customer>(root, Customer.class, customer);
     
            XMLOutputFactory xof = XMLOutputFactory.newFactory();
            XMLStreamWriter xsw = xof.createXMLStreamWriter(System.out);
            xsw.writeStartDocument();
            xsw.writeStartElement("S", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
            xsw.writeStartElement("S", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
            xsw.writeStartElement("ns0", "findCustomerResponse", "http://service.jaxws.blog/");
     
            JAXBContext jc = JAXBContext.newInstance(Customer.class);
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            marshaller.marshal(je, xsw);
             
            xsw.writeEndDocument();
            xsw.close();
        }
     
    }
 Output 

Below is the output from running the marshal demo.  Note that the output from running the demo code will appear on a single line, I have formatted the output here to make it easier to read.
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns0:findCustomerResponse xmlns:ns0="http://service.jaxws.blog/">
            <return id="123">
                <firstName>Jane</firstName>
                <lastName>Doe</lastName>
            </return>
        </ns0:findCustomerResponse>
    </S:Body>
</S:Envelope>
 
XML Document StAX

Published at DZone with permission of Blaise Doughan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Get the Comments From a DOCX Document in Java
  • Extracting Data From Very Large XML Files With X-definition
  • Google Cloud Document AI Basics
  • Thumbnail Generator Microservice for PDF in Spring Boot

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!