Problem with DOM LS serialization

Friday, 1 February 2013 · 6 messages · last reply 6 Feb 2013
M
Michael.Hedenus-EXT1 Feb 2013 15:26 #
Dear All, unfortunately I cannot serialize items using DOM/LS. I get an NullPointerException because Node.getParentNode() returns null. Here's the use-case:
public class Test
{
        public static void main(String[] args) throws Exception
        {
                System.setProperty("org.basex.path",
"D:\\ODX-Development-Neu\\odx-workspace\\.database");
                Context context = new Context();

                try
                {
                        //
                        // open DB and query an item
                        //
                        new Open("vag").execute(context);
                        QueryProcessor queryProcessor = new
QueryProcessor("//BASE-VARIANT[SHORT-NAME='BV_EnginContrModul1UDS']",
context);
                        Item item = queryProcessor.iter().next();

                        //
                        // serialize item, proofs that result is here
                        //
                        Serializer serializer =
queryProcessor.getSerializer(System.out);
// can the queryProcessor be closed here? queryProcessor.close();
                        serializer.serialize(item);
                        serializer.close();

                        //
                        // write with DOM fails!!!
                        //
                        org.w3c.dom.Node node =
(org.w3c.dom.Node)item.toJava();
DOMImplementationLS domImplementationLS = (DOMImplementationLS)DOMImplementationRegistry.newInstance ().getDOMImplementation("LS"); LSOutput lsOutput = domImplementationLS.createLSOutput(); lsOutput.setByteStream(System.out); LSSerializer lsSerializer = domImplementationLS.createLSSerializer(); lsSerializer.getDomConfig().setParameter( "format-pretty-print", Boolean.TRUE); lsSerializer.write(node, lsOutput);
                }
                finally
                {
                        context.close();
                }
        }
}
And the exception: Caused by: java.lang.NullPointerException at com.sun.org.apache.xml.internal.serialize.DOMSerializerImpl.prepareForSerialization( DOMSerializerImpl.java:1064) at com.sun.org.apache.xml.internal.serialize.DOMSerializerImpl.write( DOMSerializerImpl.java:747) ... 1 more I am using the latest snapshot: BaseX76-20130131.202759 Can you help me? Mit freundlichen Grüßen/Best regards Dr. Michael Hedenus Software Developer Powertrain Engine Systems CSW ETV RGB T2 PIXEL GmbH Im Gewerbepark C15, 93059 Regensburg, Germany Telefon/Phone: +49 941 790-6362 Telefax: +49 941 79013-90771 E-Mail: michael.hedenus-ext at continental-corporation.com www.continental-corporation.com ______________________________________________________________________ Continental Automotive GmbH, Siemensstr. 12, 93055 Regensburg, Germany Geschäftsführer/Managing Directors: Helmut Matschi, Gérard Cordonnier, Harald Stuhlmann Sitz der Gesellschaft/Registered office: Hannover Registergericht/Commercial registry: Hannover, HRB 59424, USt-Id. Nr. DE814950663 _______________________________________________________________________ Proprietary and confidential. Distribution only by express authority of Continental AG or its subsidiaries.
CG
Christian Grün1 Feb 2013 18:36 #
Dear Michael, could you provide us with a small, self-contained example that allows us to reproduce the bug? Thanks; greetings to my home town, Christian ___________________________ Dr. Christian Grün Box 188, Uni KN D-78457 Konstanz http://christian-gruen.de
Quoted text · Michael.Hedenus-EXT · 114 lines
On Fri, Feb 1, 2013 at 3:26 PM, <Michael.Hedenus-EXT at continental-corporation.com> wrote: > Dear All, > > unfortunately I cannot serialize items using DOM/LS. > I get an NullPointerException because Node.getParentNode() returns null. > > Here's the use-case: > > > > public class Test > { > public static void main(String[] args) throws Exception > { > System.setProperty("org.basex.path", > "D:\\ODX-Development-Neu\\odx-workspace\\.database"); > Context context = new Context(); > > try > { > // > // open DB and query an item > // > new Open("vag").execute(context); > QueryProcessor queryProcessor = new > QueryProcessor("//BASE-VARIANT[SHORT-NAME='BV_EnginContrModul1UDS']", > context); > Item item = queryProcessor.iter().next(); > > // > // serialize item, proofs that result is here > // > Serializer serializer = > queryProcessor.getSerializer(System.out); > > // can the queryProcessor be closed here? > queryProcessor.close(); > > serializer.serialize(item); > serializer.close(); > > // > // write with DOM fails!!! > // > org.w3c.dom.Node node = > (org.w3c.dom.Node)item.toJava(); > > DOMImplementationLS domImplementationLS = > (DOMImplementationLS)DOMImplementationRegistry.newInstance().getDOMImplementation("LS"); > LSOutput lsOutput = > domImplementationLS.createLSOutput(); > lsOutput.setByteStream(System.out); > LSSerializer lsSerializer = > domImplementationLS.createLSSerializer(); > > lsSerializer.getDomConfig().setParameter("format-pretty-print", > Boolean.TRUE); > lsSerializer.write(node, lsOutput); > > } > finally > { > context.close(); > } > } > } > > > And the exception: > > Caused by: java.lang.NullPointerException > at > com.sun.org.apache.xml.internal.serialize.DOMSerializerImpl.prepareForSerialization(DOMSerializerImpl.java:1064) > at > com.sun.org.apache.xml.internal.serialize.DOMSerializerImpl.write(DOMSerializerImpl.java:747) > ... 1 more > > > I am using the latest snapshot: BaseX76-20130131.202759 > > > Can you help me? > > > > Mit freundlichen Grüßen/Best regards > Dr. Michael Hedenus > Software Developer > Powertrain Engine Systems CSW ETV RGB T2 > PIXEL GmbH > Im Gewerbepark C15, 93059 Regensburg, Germany > > Telefon/Phone: +49 941 790-6362 > Telefax: +49 941 79013-90771 > E-Mail: michael.hedenus-ext at continental-corporation.com > www.continental-corporation.com > ______________________________________________________________________ > Continental Automotive GmbH, Siemensstr. 12, 93055 Regensburg, Germany > Geschäftsführer/Managing Directors: Helmut Matschi, Gérard Cordonnier, > Harald Stuhlmann > Sitz der Gesellschaft/Registered office: Hannover > Registergericht/Commercial registry: Hannover, HRB 59424, USt-Id. Nr. > DE814950663 > _______________________________________________________________________ > Proprietary and confidential. Distribution only by express authority of > Continental AG or its > subsidiaries. > > _______________________________________________ > BaseX-Talk mailing list > BaseX-Talk at mailman.uni-konstanz.de > https://mailman.uni-konstanz.de/mailman/listinfo/basex-talk >
CG
Christian Grün4 Feb 2013 23:02 #
Hi Michael, the problem should be fixed with the latest snapshot. Best, Christian
Quoted text · Christian Grün · 132 lines
On Fri, Feb 1, 2013 at 6:36 PM, Christian Grün <christian.gruen at gmail.com> wrote: > Dear Michael, > > could you provide us with a small, self-contained example that allows > us to reproduce the bug? > > Thanks; greetings to my home town, > Christian > ___________________________ > > Dr. Christian Grün > Box 188, Uni KN > D-78457 Konstanz > http://christian-gruen.de > > > > On Fri, Feb 1, 2013 at 3:26 PM, > <Michael.Hedenus-EXT at continental-corporation.com> wrote: >> Dear All, >> >> unfortunately I cannot serialize items using DOM/LS. >> I get an NullPointerException because Node.getParentNode() returns null. >> >> Here's the use-case: >> >> >> >> public class Test >> { >> public static void main(String[] args) throws Exception >> { >> System.setProperty("org.basex.path", >> "D:\\ODX-Development-Neu\\odx-workspace\\.database"); >> Context context = new Context(); >> >> try >> { >> // >> // open DB and query an item >> // >> new Open("vag").execute(context); >> QueryProcessor queryProcessor = new >> QueryProcessor("//BASE-VARIANT[SHORT-NAME='BV_EnginContrModul1UDS']", >> context); >> Item item = queryProcessor.iter().next(); >> >> // >> // serialize item, proofs that result is here >> // >> Serializer serializer = >> queryProcessor.getSerializer(System.out); >> >> // can the queryProcessor be closed here? >> queryProcessor.close(); >> >> serializer.serialize(item); >> serializer.close(); >> >> // >> // write with DOM fails!!! >> // >> org.w3c.dom.Node node = >> (org.w3c.dom.Node)item.toJava(); >> >> DOMImplementationLS domImplementationLS = >> (DOMImplementationLS)DOMImplementationRegistry.newInstance().getDOMImplementation("LS"); >> LSOutput lsOutput = >> domImplementationLS.createLSOutput(); >> lsOutput.setByteStream(System.out); >> LSSerializer lsSerializer = >> domImplementationLS.createLSSerializer(); >> >> lsSerializer.getDomConfig().setParameter("format-pretty-print", >> Boolean.TRUE); >> lsSerializer.write(node, lsOutput); >> >> } >> finally >> { >> context.close(); >> } >> } >> } >> >> >> And the exception: >> >> Caused by: java.lang.NullPointerException >> at >> com.sun.org.apache.xml.internal.serialize.DOMSerializerImpl.prepareForSerialization(DOMSerializerImpl.java:1064) >> at >> com.sun.org.apache.xml.internal.serialize.DOMSerializerImpl.write(DOMSerializerImpl.java:747) >> ... 1 more >> >> >> I am using the latest snapshot: BaseX76-20130131.202759 >> >> >> Can you help me? >> >> >> >> Mit freundlichen Grüßen/Best regards >> Dr. Michael Hedenus >> Software Developer >> Powertrain Engine Systems CSW ETV RGB T2 >> PIXEL GmbH >> Im Gewerbepark C15, 93059 Regensburg, Germany >> >> Telefon/Phone: +49 941 790-6362 >> Telefax: +49 941 79013-90771 >> E-Mail: michael.hedenus-ext at continental-corporation.com >> www.continental-corporation.com >> ______________________________________________________________________ >> Continental Automotive GmbH, Siemensstr. 12, 93055 Regensburg, Germany >> Geschäftsführer/Managing Directors: Helmut Matschi, Gérard Cordonnier, >> Harald Stuhlmann >> Sitz der Gesellschaft/Registered office: Hannover >> Registergericht/Commercial registry: Hannover, HRB 59424, USt-Id. Nr. >> DE814950663 >> _______________________________________________________________________ >> Proprietary and confidential. Distribution only by express authority of >> Continental AG or its >> subsidiaries. >> >> _______________________________________________ >> BaseX-Talk mailing list >> BaseX-Talk at mailman.uni-konstanz.de >> https://mailman.uni-konstanz.de/mailman/listinfo/basex-talk >>
M
Michael.Hedenus-EXT5 Feb 2013 09:13 #
Dear Christian, thank you for quickly attacking the problem! But sorry, but the problem is not fixed.I get the same error. I have a general note. I have implemented a special serializer which implements org.xml.sax .XMLReader. This is used to directly dispatch the query result to JAXB and to created objects. I can now extend this technique to generate a new DOM by implementing a SAX ContentHandler which generates a DOM. Unfortunately the serializer API is not documented nor stable (it changed from 7.3 to 7.5). I propose to add a standard SAX serializer to BaseX. This would be a very useful extension. Here is my implementation:
import static org.basex.util.Token.XMLNS;
import static org.basex.util.Token.startsWith;
import static org.basex.util.Token.string;
import static org.basex.util.Token.substring;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.basex.io.serial.Serializer;
import org.basex.query.value.item.Item;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.AttributesImpl;
/** * Bridge to translate BaseX items to SAX events. * The parse() methods does the following: * <ol> * <li>notify startDocument()</li> * <li>serialize the item</li> * <li>notify endDocument()</li> */ public class FragmentSerializer extends Serializer implements XMLReader { /** * The item to be serialized */ private Item item;
        private ContentHandler contentHandler;
        private EntityResolver entityResolver;
        private DTDHandler dtdHandler;
        private ErrorHandler errorHandler;
        private LexicalHandler lexicalHandler;

        public FragmentSerializer()
        {
        }

        public Item getItem()
        {
                return item;
        }
/** * Sets the item to be serialized. */ public void setItem(Item item) { this.item = item; }
        //////////////////////////////////////////////////
        // XMLReader
        //////////////////////////////////////////////////

        @Override
        public ContentHandler getContentHandler()
        {
                return contentHandler;
        }

        @Override
        public boolean getFeature(final String name)
        {
                return false;
        }

        @Override
        public Object getProperty(final String name)
        {
                return null;
        }

        public void parse() throws SAXException
        {
                parse("");
        }

        @Override
        public void parse(final InputSource input) throws SAXException
        {
                parse("");
        }

        @Override
        public void parse(final String id) throws SAXException
        {
                try
                {
                        contentHandler.startDocument();
                        item.serialize(this);
                        contentHandler.endDocument();
                }
                catch (final Exception ex)
                {
                        throw new SAXException(ex);
                }
        }

        @Override
        public void setContentHandler(final ContentHandler c)
        {
                contentHandler = c;
        }

        public void setLexicalHandler(final LexicalHandler l)
        {
                lexicalHandler = l;
        }

        @Override
        public void setEntityResolver(EntityResolver entityResolver)
        {
                this.entityResolver = entityResolver;
        }

        @Override
        public EntityResolver getEntityResolver()
        {
                return entityResolver;
        }

        @Override
        public void setDTDHandler(DTDHandler dtdHandler)
        {
                this.dtdHandler = dtdHandler;
        }

        @Override
        public DTDHandler getDTDHandler()
        {
                return dtdHandler;
        }

        @Override
        public void setErrorHandler(ErrorHandler errorHandler)
        {
                this.errorHandler = errorHandler;
        }

        @Override
        public ErrorHandler getErrorHandler()
        {
                return errorHandler;
        }

        @Override
        public void setFeature(final String name, final boolean value)
throws SAXNotRecognizedException, SAXNotSupportedException
        {
                throw new SAXNotRecognizedException();
        }

        @Override
        public void setProperty(final String name, final Object value)
throws SAXNotRecognizedException, SAXNotSupportedException
        {
                throw new SAXNotRecognizedException();
        }

        //////////////////////////////////////////////////
        // Serializer
        //////////////////////////////////////////////////

        private final HashMap<String, String> attributes = new
HashMap<String, String>();
        private NSDecl namespaces;

        @Override
        protected void startOpen(byte[] n) throws IOException
        {
                attributes.clear();
                this.namespaces = new NSDecl(this.namespaces);
        }

        @Override
        protected void attribute(byte[] n, byte[] v) throws IOException
        {
                String value = string(v);

                String prefix = null;
                if (startsWith(n, XMLNS))
                {
                        if (n.length == 5)
                        {
                                prefix = "";
                        }
                        else if (n[5] == ':')
                        {
                                prefix = string(substring(n, 6));
                        }
                }

                if (prefix != null)
                {
                        namespaces.put(prefix, value);
                }
                else
                {
                        String name = string(n);
                        attributes.put(name, value);
                }
        }

        @Override
        protected void finishOpen() throws IOException
        {
                try
                {
                        AttributesImpl attrs = new AttributesImpl();
                        for (Map.Entry<String, String> e :
attributes.entrySet())
                        {
                                String rname = e.getKey();
                                String[] qname = qname(rname);
                                String ns = namespaces.get(qname[0]);
                                String lname = qname[1];
                                attrs.addAttribute(ns, lname, rname, null,
e.getValue());
                        }

                        String rname = string(elem);
                        String[] qname = qname(rname);
                        String ns = namespaces.get(qname[0]);
                        String lname = qname[1];
                        contentHandler.startElement(ns, lname, rname,
attrs);

//                      System.out.println("{" + ns + "}" + lname);
//                      for (int i = 0; i < attrs.getLength(); i++)
//                      {
//                              System.out.println("    {" +
attrs.getURI(i) + "}" + attrs.getLocalName(i) + "=" + attrs.getValue(i));
//                      }
                }
                catch (final SAXException e)
                {
                        throw new IOException(e.getMessage());
                }
        }

        public String[] qname(String rname)
        {
                String prefix = "";
                String lname = rname;

                int i = rname.indexOf(':');
                if (i > 0)
                {
                        prefix = rname.substring(0, i);
                        lname = rname.substring(i + 1);
                }
                return new String[] { prefix, lname };
        }

        @Override
        protected void finishEmpty() throws IOException
        {
                finishOpen();
                finishClose();
        }

        @Override
        protected void finishClose() throws IOException
        {
                try
                {
                        String name = string(elem);
                        contentHandler.endElement("", name, name);
                        this.namespaces = namespaces.getParent();
                }
                catch (final SAXException e)
                {
                        throw new IOException(e.getMessage());
                }
        }

        @Override
        protected void finishText(byte[] text) throws IOException
        {
                try
                {
                        String s = string(text);
                        final char[] c = s.toCharArray();
                        contentHandler.characters(c, 0, c.length);
                }
                catch (final SAXException e)
                {
                        throw new IOException(e.getMessage());
                }
        }

        @Override
        protected void finishComment(byte[] comment) throws IOException
        {
                if (lexicalHandler != null)
                {
                        try
                        {
                                String s = string(comment);
                                final char[] c = s.toCharArray();
                                lexicalHandler.comment(c, 0, c.length);
                        }
                        catch (final SAXException e)
                        {
                                throw new IOException(e.getMessage());
                        }
                }
        }

        @Override
        protected void finishPi(byte[] n, byte[] v) throws IOException
        {
                //ignored
        }

        @Override
        protected void atomic(Item i) throws IOException
        {
                //ignored
        }
}

class NSDecl
{
        private final NSDecl parent;
        private Map<String, String> decls;

        public NSDecl(NSDecl parent)
        {
                this.parent = parent;
        }

        public NSDecl getParent()
        {
                return parent;
        }

        public void put(String prefix, String uri)
        {
                if (decls == null)
                {
                        decls = new HashMap<String, String>();
                }
                decls.put(prefix, uri);
        }

        public String get(String prefix)
        {
                String ns = null;
                for (NSDecl c = this; c != null; c = c.parent)
                {
                        if (c.decls != null)
                        {
                                ns = c.decls.get(prefix);
                                if (ns != null)
                                {
                                        break;
                                }
                        }
                }
                return ns != null ? ns : "";
        }
}
CG
Christian Grün5 Feb 2013 13:43 #
Quoted text · Michael.Hedenus-EXT · 1 line
> thank you for quickly attacking the problem! But sorry, but the problem is not fixed.I get the same error.
The parent references within the serialized node fragment should now be correctly resolved. Do you have an idea what could be the reason for the NPE?
Quoted text · Michael.Hedenus-EXT · 4 lines
> [...] > I propose to add a standard SAX serializer to BaseX. This would be a very useful extension. > > Here is my implementation:
Thanks. I have slightly reworked your code and added it to our code base [1]. Could you give us some feedback if it works as expected? By the way, I have added a parse(Item) function in order to ensure that an item has been specified when starting the parsing process. By the way, it would be great if you could contribute one or more minimized test methods which we could then embed as JUnit test. This will ensure that your code will continue to work as expected.. Christian [1] https://github.com/BaseXdb/basex/commit/eb7e1d51de6a6634e9b858976a683d9cb3cffdff
Quoted text · Michael.Hedenus-EXT · 372 lines
> import static org.basex.util.Token.XMLNS; > import static org.basex.util.Token.startsWith; > import static org.basex.util.Token.string; > import static org.basex.util.Token.substring; > > import java.io.IOException; > import java.util.HashMap; > import java.util.Map; > > import org.basex.io.serial.Serializer; > import org.basex.query.value.item.Item; > import org.xml.sax.ContentHandler; > import org.xml.sax.DTDHandler; > import org.xml.sax.EntityResolver; > import org.xml.sax.ErrorHandler; > import org.xml.sax.InputSource; > import org.xml.sax.SAXException; > import org.xml.sax.SAXNotRecognizedException; > import org.xml.sax.SAXNotSupportedException; > import org.xml.sax.XMLReader; > import org.xml.sax.ext.LexicalHandler; > import org.xml.sax.helpers.AttributesImpl; > > /** > * Bridge to translate BaseX items to SAX events. > * The parse() methods does the following: > * <ol> > * <li>notify startDocument()</li> > * <li>serialize the item</li> > * <li>notify endDocument()</li> > */ > public class FragmentSerializer extends Serializer implements XMLReader > { > /** > * The item to be serialized > */ > private Item item; > > private ContentHandler contentHandler; > private EntityResolver entityResolver; > private DTDHandler dtdHandler; > private ErrorHandler errorHandler; > private LexicalHandler lexicalHandler; > > public FragmentSerializer() > { > } > > public Item getItem() > { > return item; > } > > /** > * Sets the item to be serialized. > */ > public void setItem(Item item) > { > this.item = item; > } > > ////////////////////////////////////////////////// > // XMLReader > ////////////////////////////////////////////////// > > @Override > public ContentHandler getContentHandler() > { > return contentHandler; > } > > @Override > public boolean getFeature(final String name) > { > return false; > } > > @Override > public Object getProperty(final String name) > { > return null; > } > > public void parse() throws SAXException > { > parse(""); > } > > @Override > public void parse(final InputSource input) throws SAXException > { > parse(""); > } > > @Override > public void parse(final String id) throws SAXException > { > try > { > contentHandler.startDocument(); > item.serialize(this); > contentHandler.endDocument(); > } > catch (final Exception ex) > { > throw new SAXException(ex); > } > } > > @Override > public void setContentHandler(final ContentHandler c) > { > contentHandler = c; > } > > public void setLexicalHandler(final LexicalHandler l) > { > lexicalHandler = l; > } > > @Override > public void setEntityResolver(EntityResolver entityResolver) > { > this.entityResolver = entityResolver; > } > > @Override > public EntityResolver getEntityResolver() > { > return entityResolver; > } > > @Override > public void setDTDHandler(DTDHandler dtdHandler) > { > this.dtdHandler = dtdHandler; > } > > @Override > public DTDHandler getDTDHandler() > { > return dtdHandler; > } > > @Override > public void setErrorHandler(ErrorHandler errorHandler) > { > this.errorHandler = errorHandler; > } > > @Override > public ErrorHandler getErrorHandler() > { > return errorHandler; > } > > @Override > public void setFeature(final String name, final boolean value) throws SAXNotRecognizedException, SAXNotSupportedException > { > throw new SAXNotRecognizedException(); > } > > @Override > public void setProperty(final String name, final Object value) throws SAXNotRecognizedException, SAXNotSupportedException > { > throw new SAXNotRecognizedException(); > } > > ////////////////////////////////////////////////// > // Serializer > ////////////////////////////////////////////////// > > private final HashMap<String, String> attributes = new HashMap<String, String>(); > private NSDecl namespaces; > > @Override > protected void startOpen(byte[] n) throws IOException > { > attributes.clear(); > this.namespaces = new NSDecl(this.namespaces); > } > > @Override > protected void attribute(byte[] n, byte[] v) throws IOException > { > String value = string(v); > > String prefix = null; > if (startsWith(n, XMLNS)) > { > if (n.length == 5) > { > prefix = ""; > } > else if (n[5] == ':') > { > prefix = string(substring(n, 6)); > } > } > > if (prefix != null) > { > namespaces.put(prefix, value); > } > else > { > String name = string(n); > attributes.put(name, value); > } > } > > @Override > protected void finishOpen() throws IOException > { > try > { > AttributesImpl attrs = new AttributesImpl(); > for (Map.Entry<String, String> e : attributes.entrySet()) > { > String rname = e.getKey(); > String[] qname = qname(rname); > String ns = namespaces.get(qname[0]); > String lname = qname[1]; > attrs.addAttribute(ns, lname, rname, null, e.getValue()); > } > > String rname = string(elem); > String[] qname = qname(rname); > String ns = namespaces.get(qname[0]); > String lname = qname[1]; > contentHandler.startElement(ns, lname, rname, attrs); > > // System.out.println("{" + ns + "}" + lname); > // for (int i = 0; i < attrs.getLength(); i++) > // { > // System.out.println(" {" + attrs.getURI(i) + "}" + attrs.getLocalName(i) + "=" + attrs.getValue(i)); > // } > } > catch (final SAXException e) > { > throw new IOException(e.getMessage()); > } > } > > public String[] qname(String rname) > { > String prefix = ""; > String lname = rname; > > int i = rname.indexOf(':'); > if (i > 0) > { > prefix = rname.substring(0, i); > lname = rname.substring(i + 1); > } > return new String[] { prefix, lname }; > } > > @Override > protected void finishEmpty() throws IOException > { > finishOpen(); > finishClose(); > } > > @Override > protected void finishClose() throws IOException > { > try > { > String name = string(elem); > contentHandler.endElement("", name, name); > this.namespaces = namespaces.getParent(); > } > catch (final SAXException e) > { > throw new IOException(e.getMessage()); > } > } > > @Override > protected void finishText(byte[] text) throws IOException > { > try > { > String s = string(text); > final char[] c = s.toCharArray(); > contentHandler.characters(c, 0, c.length); > } > catch (final SAXException e) > { > throw new IOException(e.getMessage()); > } > } > > @Override > protected void finishComment(byte[] comment) throws IOException > { > if (lexicalHandler != null) > { > try > { > String s = string(comment); > final char[] c = s.toCharArray(); > lexicalHandler.comment(c, 0, c.length); > } > catch (final SAXException e) > { > throw new IOException(e.getMessage()); > } > } > } > > @Override > protected void finishPi(byte[] n, byte[] v) throws IOException > { > //ignored > } > > @Override > protected void atomic(Item i) throws IOException > { > //ignored > } > } > > class NSDecl > { > private final NSDecl parent; > private Map<String, String> decls; > > public NSDecl(NSDecl parent) > { > this.parent = parent; > } > > public NSDecl getParent() > { > return parent; > } > > public void put(String prefix, String uri) > { > if (decls == null) > { > decls = new HashMap<String, String>(); > } > decls.put(prefix, uri); > } > > public String get(String prefix) > { > String ns = null; > for (NSDecl c = this; c != null; c = c.parent) > { > if (c.decls != null) > { > ns = c.decls.get(prefix); > if (ns != null) > { > break; > } > } > } > return ns != null ? ns : ""; > } > } > _______________________________________________ > BaseX-Talk mailing list > BaseX-Talk at mailman.uni-konstanz.de > https://mailman.uni-konstanz.de/mailman/listinfo/basex-talk >
M
Michael.Hedenus-EXT6 Feb 2013 10:47 #
Dear Christian, I've no idea why DOM/LS still doesn't work, but with the SAXSerializer the problem is no more. When the SAXSerialier works query result can easily converted into any DOM using a simple ContentHandler implementation: /** * Constructs a DOM from SAX events. * Original idea by Florent Georges. */ public class SaxToDomHandler implements ContentHandler { private final DocumentBuilder documentBuilder;
        private Document document;
        private Node current;

        public SaxToDomHandler(DocumentBuilder documentBuilder)
        {
                this.documentBuilder = documentBuilder;
        }
/** * Returns the created document. */ public Document getDocument() { return document; }
        @Override
        public void startDocument() throws SAXException
        {
                document = documentBuilder.newDocument();
                current = document;
        }

        @Override
        public void startElement(String uri, String name, String qName,
Attributes attrs)
        {
                Element element = document.createElementNS(uri, qName);

                for (int i = 0; i < attrs.getLength(); i++)
                {
                        String nsURI = attrs.getURI(i);
                        String qname = attrs.getQName(i);
                        String value = attrs.getValue(i);

                        Attr attr = document.createAttributeNS(nsURI,
qname);
                        attr.setValue(value);
                        element.setAttributeNodeNS(attr);
                }

                current.appendChild(element);
                current = element;
        }

        @Override
        public void endElement(String uri, String name, String qName)
        {
                current = current.getParentNode();
        }

        @Override
        public void endDocument() throws SAXException
        {
                current = current.getOwnerDocument();
        }

        @Override
        public void characters(char[] ch, int start, int length)
        {
                String string = new String(ch, start, length);
                current.appendChild(document.createTextNode(string));
        }

        @Override
        public void ignorableWhitespace(char[] ch, int start, int length)
        {
                characters(ch, start, length);
        }

        @Override
        public void processingInstruction(String target, String data)
        {
                current.appendChild(document
.createProcessingInstruction(target, data));
        }

        @Override
        public void setDocumentLocator(Locator locator)
        {
                //NOP
        }

        @Override
        public void startPrefixMapping(String prefix, String uri) throws
SAXException
        {
                //NOP
        }

        @Override
        public void endPrefixMapping(String prefix) throws SAXException
        {
                //NOP
        }

        @Override
        public void skippedEntity(String name) throws SAXException
        {
                //NOP
        }
}

⚡Generated with XQuery