Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB: How can I unmarshal XML without namespaces

I have an XML file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<object>
   <str>the type</str>
   <bool type="boolean">true</bool>        
</object>

And I want to unmarshal it to an object of the class below

@XmlRootElement(name="object")
public class Spec  {
   public String str;
   public Object bool;

}

How can I do this? Unless I specify namespaces (see below), it doesn't work.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<object>
   <str>the type</str>
   <bool xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
       xmlns:xs="http://www.w3.org/2001/XMLSchema"  
       xsi:type="xs:boolean">true</bool>        
</object>
like image 270
Andrey Avatar asked Aug 25 '11 02:08

Andrey


People also ask

How do you Unmarshal XML?

To unmarshal an xml string into a JAXB object, you will need to create an Unmarshaller from the JAXBContext, then call the unmarshal() method with a source/reader and the expected root object.

Is JAXB XML parser?

JAXB — Java Architecture for XML Binding — is used to convert objects from/to XML. JAXB offers a fast and suitable way to marshal (write) Java objects into XML and unmarshal (read) XML into Java objects. It supports Java annotations to map XML elements to Java attributes.


1 Answers

An easier way might be to use unmarshalByDeclaredType, since you already know the type you want to unmarshal.

By using

Unmarshaller.unmarshal(rootNode, MyType.class);

you don't need to have a namespace declaration in the XML, since you pass in the JAXBElement that has the namespace already set.

This also perfectly legal, since you are not required to reference a namespace in an XML instance, see http://www.w3.org/TR/xmlschema-0/#PO - and many clients produce XML in that fashion.

Finally got it to work. Note that you have to remove any custom namespace in the schema; here's working sample code:

The schema:

<xsd:schema
   xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="customer">
   <xsd:complexType>
      <xsd:sequence minOccurs="1" maxOccurs="1">
         <xsd:element name="name" type="xsd:string" minOccurs="1" maxOccurs="1" />
         <xsd:element name="phone" type="xsd:string" minOccurs="1" maxOccurs="1" />
      </xsd:sequence>
   </xsd:complexType>
</xsd:element>

XML:

<?xml version="1.0" encoding="UTF-8"?>
<customer>
   <name>Jane Doe</name>
   <phone>08154712</phone>
</customer>

JAXB code:

JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller u = jc.createUnmarshaller();
u.setSchema(schemaInputStream); // load your schema from File or any streamsource
Customer = u.unmarshal(new StreamSource(inputStream), clazz);  // pass in your XML as inputStream
like image 83
Gregor Avatar answered Sep 19 '22 12:09

Gregor