wwxml.java

来自「world wind java sdk 源码」· Java 代码 · 共 1,246 行 · 第 1/4 页

JAVA
1,246
字号
/*Copyright (C) 2001, 2009 United States Governmentas represented by the Administrator of theNational Aeronautics and Space Administration.All Rights Reserved.*/package gov.nasa.worldwind.util;import gov.nasa.worldwind.Configuration;import gov.nasa.worldwind.avlist.AVList;import gov.nasa.worldwind.exception.WWRuntimeException;import gov.nasa.worldwind.geom.*;import org.w3c.dom.*;import org.xml.sax.SAXException;import javax.xml.parsers.*;import javax.xml.xpath.*;import java.io.*;import java.nio.ByteBuffer;import java.util.*;/** * A collection of static methods use for opening, reading and otherwise working with XML files. * * @author tag * @version $Id: WWXML.java 9600 2009-03-22 20:04:40Z tgaskins $ */public class WWXML{    /**     * Create a DOM builder.     *     * @param isNamespaceAware true if the builder is to be namespace aware, otherwise false.     *     * @return a {@link javax.xml.parsers.DocumentBuilder}.     *     * @throws WWRuntimeException if an error occurs.     */    public static DocumentBuilder createDocumentBuilder(boolean isNamespaceAware)    {        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();        docBuilderFactory.setNamespaceAware(isNamespaceAware);        if (Configuration.getJavaVersion() >= 1.6)        {            try            {                docBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",                    false);            }            catch (ParserConfigurationException e)            {   // Note it and continue on. Some Java5 parsers don't support the feature.                String message = Logging.getMessage("XML.NonvalidatingNotSupported");                Logging.logger().finest(message);            }        }        try        {            return docBuilderFactory.newDocumentBuilder();        }        catch (ParserConfigurationException e)        {            String message = Logging.getMessage("XML.ParserConfigurationException");            Logging.logger().finest(message);            throw new WWRuntimeException(e);        }    }    /**     * Opens an XML file given the file's location in the file system or on the classpath.     *     * @param filePath the path to the file. Must be an absolute path or a path relative to a location in the     *                 classpath.     * @param c        the class that will be used to find a path relative to the classpath.     *     * @return a DOM for the file.     *     * @throws IllegalArgumentException if the file path is null.     * @throws WWRuntimeException       if an exception or error occurs while opening and parsing the file. The causing     *                                  exception is included in this exception's {@link Throwable#initCause(Throwable)}     *                                  .     */    public static Document openDocumentFile(String filePath, Class c)    {        if (filePath == null)        {            String message = Logging.getMessage("nullValue.FileIsNull");            Logging.logger().severe(message);            throw new IllegalArgumentException(message);        }        try        {            InputStream inputStream = WWIO.openFileOrResourceStream(filePath, c);            return WWXML.createDocumentBuilder(true).parse(inputStream);        }        catch (SAXException e)        {            String message = Logging.getMessage("generic.ExceptionAttemptingToParseXml", filePath);            Logging.logger().severe(message);            throw new WWRuntimeException(e);        }        catch (IOException e)        {            String message = Logging.getMessage("generic.ExceptionAttemptingToParseXml", filePath);            Logging.logger().severe(message);            throw new WWRuntimeException(e);        }    }    /**     * Shortcut method to create an {@link XPath}.     *     * @return a new XPath.     */    public static XPath makeXPath()    {        XPathFactory xpFactory = XPathFactory.newInstance();        return xpFactory.newXPath();    }    /**     * Returns the text of the element identified by an XPath expression.     *     * @param context the context from which to start the XPath search.     * @param path    the XPath expression.     *     * @return the text of an element matching the XPath expression, or null if no match is found.     *     * @throws IllegalArgumentException if the context or XPath expression are null.     */    public static String getText(Element context, String path)    {        return getText(context, path, null);    }    public static String checkOGCException(Document doc)    {        if (doc == null)        {            String message = Logging.getMessage("nullValue.DocumentIsNull");            Logging.logger().severe(message);            throw new IllegalArgumentException(message);        }        try        {            XPath xpath = makeXPath();            String exception = xpath.evaluate("ServiceExceptionReport", doc);            if (exception == null || exception.length() == 0)                return null;            // TODO: Test this xpath expression for returning the text of the service exception.            return xpath.evaluate("ServiceExceptionReport/ServiceException/text()", doc);        }        catch (XPathExpressionException e)        {            String message = Logging.getMessage("XML.XPathExpressionException");            Logging.logger().warning(message);            return null;        }    }    public static String extractOGCServiceException(ByteBuffer buffer)    {        return null; // TODO    }    /**     * Returns the text of the element identified by an XPath expression.     *     * @param context the context from which to start the XPath search.     * @param path    the XPath expression.     * @param xpath   an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when     *                performing multiple searches. May be null.     *     * @return the text of an element matching the XPath expression, or null if no match is found.     *     * @throws IllegalArgumentException if the context or XPath expression are null.     */    public static String getText(Element context, String path, XPath xpath)    {        if (context == null)        {            String message = Logging.getMessage("nullValue.ContextIsNull");            Logging.logger().severe(message);            throw new IllegalArgumentException(message);        }        if (path == null)        {            String message = Logging.getMessage("nullValue.PathIsNull");            Logging.logger().severe(message);            throw new IllegalArgumentException(message);        }        if (xpath == null)            xpath = makeXPath();        try        {            return xpath.evaluate(path, context);        }        catch (XPathExpressionException e)        {            return null;        }    }    /**     * Returns the text of all elements identified by an XPath expression.     *     * @param context the context from which to start the XPath search.     * @param path    the XPath expression.     * @param xpath   an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when     *                performing multiple searches. May be null.     *     * @return an array containing the text of each element matching the XPath expression.     *     * @throws IllegalArgumentException if the context or XPath expression are null.     */    public static String[] getTextArray(Element context, String path, XPath xpath)    {        if (context == null)        {            String message = Logging.getMessage("nullValue.ContextIsNull");            Logging.logger().severe(message);            throw new IllegalArgumentException(message);        }        if (path == null)        {            String message = Logging.getMessage("nullValue.PathIsNull");            Logging.logger().severe(message);            throw new IllegalArgumentException(message);        }        if (xpath == null)            xpath = makeXPath();        try        {            NodeList nodes = (NodeList) xpath.evaluate(path, context,                XPathConstants.NODESET);            if (nodes == null || nodes.getLength() == 0)                return null;            String[] strings = new String[nodes.getLength()];            for (int i = 0; i < nodes.getLength(); i++)            {                strings[i] = nodes.item(i).getTextContent();            }            return strings;        }        catch (XPathExpressionException e)        {            return null;        }    }    /**     * Returns the text of all unique elements identified by an XPath expression.     *     * @param context the context from which to start the XPath search.     * @param path    the XPath expression.     * @param xpath   an {@link XPath} object to use for the search. This allows the caller to re-use XPath objects when     *                performing multiple searches. May be null.     *     * @return an array containing the text of each element matching the XPath expression and containing unique text. If     *         multiple elements contain the same text only the first one found is returned. Returns null if no matching     *         element is found.     *     * @throws IllegalArgumentException if the context or XPath expression are null.     */    public static String[] getUniqueText(Element context, String path, XPath xpath)    {        if (context == null)        {            String message = Logging.getMessage("nullValue.ContextIsNull");            Logging.logger().severe(message);            throw new IllegalArgumentException(message);        }        if (path == null)        {            String message = Logging.getMessage("nullValue.PathIsNull");            Logging.logger().severe(message);            throw new IllegalArgumentException(message);        }        if (xpath == null)            xpath = makeXPath();        String[] strings = getTextArray(context, path, xpath);        if (strings == null)            return null;        ArrayList<String> sarl = new ArrayList<String>();        for (String s : strings)        {            if (!sarl.contains(s))                sarl.add(s);        }        return sarl.toArray(new String[1]);    }

⌨️ 快捷键说明

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