users@jaxb.java.net

Re: Question on JAXB 2.0 ValidationEventHandler

From: Wolfgang Laun <wolfgang.laun_at_gmail.com>
Date: Tue, 30 Mar 2010 16:17:39 +0200

Below is a slap-dash Java program doing a DOM parse and an in-memory
unmarshalling
using the validation error handling you posted. Following it the XML file
(with an error
in it) and the XML Schema.

You'll have to download Apache's xerxes.

(Most of the code is copied from
http://www.teialehrbuch.de/Kostenlose-Kurse/XML/7767-Ein-minimaler-DOM-Parser-mit-Xerces.htmlbut
that's in German.)

-W

import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import javax.xml.bind.*;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.IOException;
import java.io.File;
import generated.*;

public class Main {
    private static void traverse (Node node) {
    int type = node.getNodeType();
    if (type == Node.ELEMENT_NODE) {
        System.out.println ("<" + node.getNodeName()+ ">");
    }

    // Verarbeitet die Liste der Kindknoten durch rekursiven Abstieg
    NodeList children = node.getChildNodes();
    for (int i=0; i< children.getLength(); i++)
        traverse (children.item(i));
    }

    private static Document parse( String xmlFile ){
        Document document = null;
    try {
        DOMParser parser = new DOMParser();
        parser.parse( xmlFile );
        document = parser.getDocument();
            traverse( document );
    } catch (SAXException e) {
        System.err.println (e);
    } catch (IOException e) {
        System.err.println (e);
    }
    return document;
    }

    public static void main( String[] args ) {
        Document xmlDocument = parse( args[0] );
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance("generated");
        Unmarshaller um = jaxbContext.createUnmarshaller();
        SchemaFactory schemaFactory =
        SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        Schema schema = schemaFactory.newSchema(new File( args[1] ));
        um.setSchema( schema );
        um.setEventHandler( new ValidationEventHandler() {
            // allow unmarshalling to continue even if there are errors
            public boolean handleEvent(ValidationEvent ve) {
            // ignore warnings
            if (ve.getSeverity() != ValidationEvent.WARNING) {
                ValidationEventLocator vel = ve.getLocator();
                System.out.println("Line:Col[" + vel.getLineNumber() +
                           ":" + vel.getColumnNumber() +
                           "]:" + ve.getMessage());

                Node badNode = vel.getNode();
                System.out.println( "Node:" + badNode );
                Node parent = badNode.getParentNode();
                System.out.println( "Parent of Node:" + parent );

            }
            return true;
            }
        }
        );
        JAXBElement<DocType> docElement =
        (JAXBElement<DocType>)um.unmarshal(xmlDocument);
    } catch( JAXBException e ){
        System.err.println (e);
    } catch (SAXException e) {
        System.err.println (e);
    }
    }
}


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<doc>
    <Tipo>
       <Count>1</Count>
    </Tipo>
</doc>

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
            version="2.0">

<xs:element name="doc" type="DocType"/>

<xs:complexType name="DocType">
  <xs:sequence>
    <xs:element name="Tipo" type="xs:string"/>
    <xs:element name="Count" type="CounterType" default="1" minOccurs="0"/>
  </xs:sequence>
  <xs:attribute name="Number" type="xs:long"/>
</xs:complexType>

<xs:simpleType name="CounterType">
  <xs:restriction base="xs:int">
    <xs:minInclusive value="0"/>
  </xs:restriction>
</xs:simpleType>

</xs:schema>





On Tue, Mar 30, 2010 at 2:39 PM, Srikanth R Chinthala <csr_1978_at_yahoo.com>wrote:

>
> Laun,
>
> Does JAXB 2.0 use SAX parser by default? How do i make it to use DOM
> parser?
>
> Could you please provide a sample code snippet. Sorry if i am asking a
> silly
> question. Please care to reply.
>
> Thanks,
>
>
> Unmarshalling with a SAX parser won't produce DOM nodes, which would be
> returned
> by Locator.getNode(). You might try to create a DOM tree from the XML file
> and
> unmarshal from that.
>
> It's strange that you might be able to "perform some business logic" on a
> broken
> XML document (except diagnose the error, of course).
>
> -W
>
> --
> View this message in context:
> http://old.nabble.com/Question-on-JAXB-2.0-ValidationEventHandler-tp28076972p28081915.html
> Sent from the java.net - jaxb users mailing list archive at Nabble.com.
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_jaxb.dev.java.net
> For additional commands, e-mail: users-help_at_jaxb.dev.java.net
>
>