⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 staxutils.java

📁 Xfire文件 用于开发web service 的一个开源工具 很好用的
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package org.codehaus.xfire.util;import java.io.InputStream;import java.io.OutputStream;import java.io.Reader;import java.util.HashMap;import java.util.Map;import javax.xml.namespace.NamespaceContext;import javax.xml.parsers.DocumentBuilder;import javax.xml.stream.XMLInputFactory;import javax.xml.stream.XMLOutputFactory;import javax.xml.stream.XMLStreamConstants;import javax.xml.stream.XMLStreamException;import javax.xml.stream.XMLStreamReader;import javax.xml.stream.XMLStreamWriter;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.codehaus.xfire.MessageContext;import org.codehaus.xfire.XFire;import org.codehaus.xfire.XFireRuntimeException;import org.codehaus.xfire.util.stax.DepthXMLStreamReader;import org.w3c.dom.Attr;import org.w3c.dom.CDATASection;import org.w3c.dom.Comment;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.EntityReference;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.w3c.dom.ProcessingInstruction;import org.w3c.dom.Text;/** * Common StAX utilities. *  * @author <a href="mailto:dan@envoisolutions.com">Dan Diephouse</a> * @since Oct 26, 2004 */public class STAXUtils{    private static final String XML_NS = "http://www.w3.org/2000/xmlns/";      private final static Log logger = LogFactory.getLog(STAXUtils.class);        private final static XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();    private final static XMLOutputFactory xmlOututFactory = XMLOutputFactory.newInstance();    private static boolean inFactoryConfigured;        private final static Map factories = new HashMap();    /**     * Returns true if currently at the start of an element, otherwise move forwards to the next     * element start and return true, otherwise false is returned if the end of the stream is reached.     */    public static boolean skipToStartOfElement(XMLStreamReader in)        throws XMLStreamException    {        for (int code = in.getEventType(); code != XMLStreamReader.END_DOCUMENT; code = in.next())        {            if (code == XMLStreamReader.START_ELEMENT)            {                return true;            }        }        return false;    }    public static boolean toNextElement(DepthXMLStreamReader dr)    {        if (dr.getEventType() == XMLStreamReader.START_ELEMENT)            return true;                if (dr.getEventType() == XMLStreamReader.END_ELEMENT)            return false;                try        {            int depth = dr.getDepth();                        for (int event = dr.getEventType(); dr.getDepth() >= depth && dr.hasNext(); event = dr.next())            {                if (event == XMLStreamReader.START_ELEMENT && dr.getDepth() == depth + 1)                {                    return true;                }                else if (event == XMLStreamReader.END_ELEMENT)                {                    depth--;                }            }                        return false;        }        catch (XMLStreamException e)        {            throw new XFireRuntimeException("Couldn't parse stream.", e);        }    }       public static boolean skipToStartOfElement(DepthXMLStreamReader in)        throws XMLStreamException    {        for (int code = in.getEventType(); code != XMLStreamReader.END_DOCUMENT; code = in.next())        {            if (code == XMLStreamReader.START_ELEMENT)            {                return true;            }        }        return false;    }        /**     * Copies the reader to the writer.  The start and end document     * methods must be handled on the writer manually.     *      * TODO: if the namespace on the reader has been declared previously     * to where we are in the stream, this probably won't work.     *      * @param reader     * @param writer     * @throws XMLStreamException     */    public static void copy( XMLStreamReader reader, XMLStreamWriter writer )         throws XMLStreamException    {        int read = 0; // number of elements read in        int event = reader.getEventType();                while ( reader.hasNext() )        {            switch( event )            {                case XMLStreamConstants.START_ELEMENT:                    read++;                    writeStartElement( reader, writer );                    break;                case XMLStreamConstants.END_ELEMENT:                    writer.writeEndElement();                    read--;                    if ( read <= 0 )                        return;                    break;                case XMLStreamConstants.CHARACTERS:                    writer.writeCharacters( reader.getText() );                      break;                case XMLStreamConstants.START_DOCUMENT:                case XMLStreamConstants.END_DOCUMENT:                case XMLStreamConstants.ATTRIBUTE:                case XMLStreamConstants.NAMESPACE:                    break;                case XMLStreamConstants.CDATA:                	writer.writeCData(reader.getText());                	break;                default:                    break;            }            event = reader.next();        }    }    private static void writeStartElement(XMLStreamReader reader, XMLStreamWriter writer)         throws XMLStreamException    {        String local = reader.getLocalName();        String uri = reader.getNamespaceURI();        String prefix = reader.getPrefix();        if (prefix == null)        {            prefix = "";        }                String boundPrefix = writer.getPrefix(uri);        boolean writeElementNS = false;        if ( boundPrefix == null || !prefix.equals(boundPrefix) )        {               writeElementNS = true;        }                // Write out the element name        if (uri != null && uri.length() > 0)        {            if (prefix.length() == 0)             {                                 writer.writeStartElement(local);                writer.setDefaultNamespace(uri);                             }             else             {                 writer.writeStartElement(prefix, local, uri);                 writer.setPrefix(prefix, uri);             }         }        else        {            writer.writeStartElement( reader.getLocalName() );        }        // Write out the namespaces        for ( int i = 0; i < reader.getNamespaceCount(); i++ )        {            String nsURI = reader.getNamespaceURI(i);            String nsPrefix = reader.getNamespacePrefix(i);                        // Why oh why does the RI suck so much?            if (nsURI == null) nsURI = "";            if (nsPrefix == null) nsPrefix = "";                        if ( nsPrefix.length() ==  0 )            {                writer.writeDefaultNamespace(nsURI);            }            else            {                writer.writeNamespace(nsPrefix, nsURI);            }            if (uri != null && nsURI.equals(uri) && nsPrefix.equals(prefix))            {                writeElementNS = false;            }        }                // Check if the namespace still needs to be written.        // We need this check because namespace writing works         // different on Woodstox and the RI.        if (writeElementNS && uri != null)        {            if ( prefix == null || prefix.length() ==  0 )            {                writer.writeDefaultNamespace(uri);            }            else            {                writer.writeNamespace(prefix, uri);            }        }        // Write out attributes        for ( int i = 0; i < reader.getAttributeCount(); i++ )        {            String ns = reader.getAttributeNamespace(i);            String nsPrefix = reader.getAttributePrefix(i);            if ( ns == null || ns.length() == 0 )            {                writer.writeAttribute(                        reader.getAttributeLocalName(i),                        reader.getAttributeValue(i));            }            else if (nsPrefix == null || nsPrefix.length() == 0)            {                writer.writeAttribute(                    reader.getAttributeNamespace(i),                    reader.getAttributeLocalName(i),                    reader.getAttributeValue(i));            }            else            {                writer.writeAttribute(reader.getAttributePrefix(i),                                      reader.getAttributeNamespace(i),                                      reader.getAttributeLocalName(i),                                      reader.getAttributeValue(i));            }        }    }    public static void writeDocument( Document d, XMLStreamWriter writer, boolean repairing )         throws XMLStreamException    {        writeDocument(d, writer, true, repairing);    }        public static void writeDocument(Document d, XMLStreamWriter writer, boolean writeProlog, boolean repairing)         throws XMLStreamException    {        if (writeProlog) writer.writeStartDocument();                Element root = d.getDocumentElement();        writeElement(root, writer, repairing);                if (writeProlog) writer.writeEndDocument();    }    /**     * Writes an Element to an XMLStreamWriter.  The writer must already     * have started the doucment (via writeStartDocument()). Also, this probably     * won't work with just a fragment of a document. The Element should be     * the root element of the document.     *      * @param e     * @param writer     * @throws XMLStreamException     */    public static void writeElement( Element e, XMLStreamWriter writer, boolean repairing )         throws XMLStreamException    {        String prefix = e.getPrefix();        String ns = e.getNamespaceURI();        String localName = e.getLocalName();        if (prefix == null) prefix = "";        if (localName == null)         {            localName = e.getNodeName();                        if (localName == null)                throw new IllegalStateException("Element's local name cannot be null!");        }                    String decUri = null;        NamespaceContext ctxt = writer.getNamespaceContext();        if (ctxt != null) {        	decUri = ctxt.getNamespaceURI(prefix);        }        boolean declareNamespace = (decUri == null || !decUri.equals(ns));        if (ns == null || ns.length() == 0)        {            writer.writeStartElement( localName );        }        else        {            writer.writeStartElement(prefix, localName, ns);        }        NamedNodeMap attrs = e.getAttributes();        for ( int i = 0; i < attrs.getLength(); i++ )        {            Node attr = attrs.item(i);                        String name = attr.getNodeName();            String attrPrefix = "";            int prefixIndex = name.indexOf(':');            if (prefixIndex != -1)            {                attrPrefix = name.substring(0, prefixIndex);                name = name.substring(prefixIndex+1);            }            if (attrPrefix.equals("xmlns"))            {            	writer.writeNamespace(name, attr.getNodeValue());                if (name.equals(prefix) && attr.getNodeValue().equals(ns))                {                    declareNamespace = false;                }            }            else            {            	if (name.equals("xmlns") && attrPrefix.equals(""))            	{            		writer.writeNamespace("", attr.getNodeValue());            		if (attr.getNodeValue().equals(ns))             		{            			declareNamespace = false;            		}            	}             	else            	{            		writer.writeAttribute(attrPrefix, attr.getNamespaceURI(), name, attr.getNodeValue());                }            }        }        if (declareNamespace && repairing)        {            writer.writeNamespace(prefix, ns);        }                NodeList nodes = e.getChildNodes();        for ( int i = 0; i < nodes.getLength(); i++ )        {            Node n = nodes.item(i);            writeNode(n, writer, repairing);        }        writer.writeEndElement();    }    public static void writeNode(Node n, XMLStreamWriter writer, boolean repairing)        throws XMLStreamException    {        if ( n instanceof Element )        {            writeElement((Element)n, writer, repairing);        }        else if ( n instanceof Text )        {            writer.writeCharacters(((Text) n).getNodeValue());        }        else if ( n instanceof CDATASection )

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -