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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • How To Get the Comments From a DOCX Document in Java
  • How To Create and Edit PDF Annotations in Java
  • How to Merge HTML Documents in Java
  • How to Convert XLS to XLSX in Java

Trending

  • Designing for Sustainability: The Rise of Green Software
  • My Favorite Interview Question
  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
  1. DZone
  2. Coding
  3. Languages
  4. Applying a Namespace During JAXB Unmarshal

Applying a Namespace During JAXB Unmarshal

By 
Blaise Doughan user avatar
Blaise Doughan
·
Nov. 10, 12 · Interview
Likes (1)
Comment
Save
Tweet
Share
63.5K Views

Join the DZone community and get the full member experience.

Join For Free

 For some an XML schema is a strict set of rules for how the XML document must be structured.  But for others it is a general guideline to indicate what the XML should look like.  This means that sometimes people want to accept input that doesn't conform to the XML schema for some reason.  In this example I will demonstrate how this can be done by leveraging a SAX XMLFilter.

Java Model

Below is the Java model that will be used for this example.

Customer
package blog.namespace.sax;
 
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement
public class Customer {
 
    private String name;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
}
package-info
We will use the package level @XmlSchema annotation to specify the namespace qualification for our model.
@XmlSchema(
        namespace="http://www.example.com/customer",
        elementFormDefault=XmlNsForm.QUALIFIED)
package blog.namespace.sax;
 
import javax.xml.bind.annotation.*;

XML Input (input.xml)

Even though our metadata specified that all the elements should be qualified with a namespace (http://www.example.com/customer) our input document is not namespace qualified.  An XMLFilter will be used to add the namespace during the unmarshal operation.
<?xml version="1.0" encoding="UTF-8"?>
<customer>
    <name>Jane Doe</name>
</customer>
XMLFilter (NamespaceFilter) 

The easiest way to create an XMLFilter is to extend XMLFilterImpl.  For our use case we will override the startElement and endElement methods.  In each of these methods we will call the corresponding super method passing in the default namespace as the URI parameter.
package blog.namespace.sax;
 
import org.xml.sax.*;
import org.xml.sax.helpers.XMLFilterImpl;
 
public class NamespaceFilter extends XMLFilterImpl {
 
    private static final String NAMESPACE = "http://www.example.com/customer";
 
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        super.endElement(NAMESPACE, localName, qName);
    }
 
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes atts) throws SAXException {
        super.startElement(NAMESPACE, localName, qName, atts);
    }
 
}

Demo

In the demo code below we will do a SAX parse of the XML document.  The XMLReader will be wrapped in our XMLFilter.  We will leverage JAXB's UnmarshallerHandler as the ContentHandler.  Once the parse has been done we can ask the UnmarshallerHandler for the resulting Customer object.
package blog.namespace.sax;
 
import javax.xml.bind.*;
import javax.xml.parsers.*;
import org.xml.sax.*;
 
public class Demo {
 
    public static void main(String[] args) throws Exception {
        // Create the JAXBContext
        JAXBContext jc = JAXBContext.newInstance(Customer.class);
 
        // Create the XMLFilter
        XMLFilter filter = new NamespaceFilter();
 
        // Set the parent XMLReader on the XMLFilter
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        filter.setParent(xr);
 
        // Set UnmarshallerHandler as ContentHandler on XMLFilter
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        UnmarshallerHandler unmarshallerHandler = unmarshaller
                .getUnmarshallerHandler();
        filter.setContentHandler(unmarshallerHandler);
 
        // Parse the XML
        InputSource xml = new InputSource("src/blog/namespace/sax/input.xml");
        filter.parse(xml);
        Customer customer = (Customer) unmarshallerHandler.getResult();
 
        // Marshal the Customer object back to XML
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(customer, System.out);
    }
 
}

Output

Below is the output from running the demo code.  Note how the output contains the namespace qualification based on the metadata.
<?xml version="1.0" encoding="UTF-8"?>
<customer xmlns="http://www.example.com/customer">
    <name>Jane Doe</name>
</customer>

Further Reading 

If you enjoyed this post then you may also be interested in:
  • JAXB & Namespaces
  • Preventing Entity Expansion Attacks in JAXB


XML Use case Document Schema Metadata Java (programming language) Leverage (statistics) Annotation POST (HTTP)

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
  • How To Create and Edit PDF Annotations in Java
  • How to Merge HTML Documents in Java
  • How to Convert XLS to XLSX in Java

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!