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

📄 xmltools.java

📁 基于MPEG 7 标准,符合未来语义网架构,很值得参考
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
            URL url = FileTools.getFileURL(fileName, null);
            if (url == null) {
                fileName = "";
            } else {
                fileName = url.toExternalForm();
            }

            DocType docType = new DocType(rootElement, fileName);

            docOrginal.setDocType(docType);
            String strDocDtd = documentToString(docOrginal);
            cat.debug("strdocdtd: " + strDocDtd);

            Document docDtd = stringToDocument(strDocDtd, true);
            if (docDtd == null)
                return ret;
            ret = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ret;
    }


    // make a String, that represents the jaxb-tree
    /*public static String jaxbSerialize(MarshallableRootElement element1) {

        String ret = ConvertValues.buildErrorResponse("unable to generate xml-stream");
        try {
            OutputStream os = new ByteArrayOutputStream();
            element1.validate();
            element1.marshal(os);
            ret = os.toString();
            os.close();

        } catch (Exception e) {
            console.exitOnException(e);
        }
        return ret;
    }
*/
    /*   // sava jaxb-tree to a xml-file
       public static void jaxbSaveToFile(String filename1, MarshallableRootElement element1) {
           try {
               OutputStream os = new FileOutputStream(filename1);
               element1.validate();
               element1.marshal(os);
               os.close();

           } catch (Exception e) {
               console.exitOnException(e);
           }
       } // end method*/


    // lazy comparision. removes all #10,#13, tabs and spaces from the Strings
    // and compares them.
    // problem: the order of attributes may differ => method returns false
    /*public static boolean compareXml(String xml1, String xml2) {
        String in1 = xml1;
        String in2 = xml2;


        char[] ascChar = new char[1];
        ascChar[0] = 9;
        String asc_09 = new String(ascChar);
        ascChar[0] = 10;
        String asc_10 = new String(ascChar);
        ascChar[0] = 13;
        String asc_13 = new String(ascChar);

        in1 = StringTools.replace(in1, asc_10, "");
        in2 = StringTools.replace(in2, asc_10, "");

        in1 = StringTools.replace(in1, asc_13, "");
        in2 = StringTools.replace(in2, asc_13, "");

        in1 = StringTools.replace(in1, asc_09, "");
        in2 = StringTools.replace(in2, asc_09, "");

        in1 = StringTools.replace(in1, " ", "");
        in2 = StringTools.replace(in2, " ", "");

        //cat.debug("str1: \"" + in1 + "\"");
        //cat.debug("str2: \"" + in2 + "\"");

        FileTools.saveToFile(cfg.getTestOutputDir() + "in1.txt", in1);
        FileTools.saveToFile(cfg.getTestOutputDir() + "in2.txt", in2);





        //return in1.equals(in2);
        return in1.length() == in2.length();
    }*/


    // input String is a xpath query and the document to search
    // output is a list of all matching Elements
    public static List<Element> xpathQuery(org.jdom.Document document, String xpathQuery1, Namespace xNs) {
        List<Element> returnValue = new ArrayList<Element>();
        String xpathQuery = xpathQuery1;
        XPath xPath;
        try {
            if (document == null || document.getRootElement() == null) {
                return returnValue; //------------- EXIT POINT -------------
            }

            // if there is a xmlns namespace wihtout a prefix, then
            // a default one has to be added. Otherwise jaxen does not work
            // Note: the prefix "x" has to be used in the xpath-query as well.
            Namespace ns = document.getRootElement().getNamespace();
            if (ns.getPrefix().length() == 0) {
                /*
                StringTokenizer tokens = new StringTokenizer(xpathQuery, "/", true);
                xpathQuery = "";
                while (tokens.hasMoreTokens()) {
                    String token = tokens.nextToken();
                    if (!token.equalsIgnoreCase("/")) {
                        token = "x:" + token;
                    }
                    xpathQuery += token;
                }*/

                //xPath = new JDOMXPath(xpathQuery);
                xPath = XPath.newInstance(xpathQuery);
                //xPath.addNamespace(ns);

                String uri = ns.getURI();
                if (uri == null || uri.length() == 0) {
                    uri = "dummy";
                }
                //System.out.println("uir: \"" + uri + "\"");
                //xPath.addNamespace("x", uri);
            } else {
                //xPath = new JDOMXPath(xpathQuery);
                xPath = XPath.newInstance(xpathQuery);
                xPath.addNamespace(ns);
            }

            if (xNs != null) {
                xPath.addNamespace(xNs.getPrefix(), xNs.getURI());
            }

            //cat.debug("OLD: \"" + xpathQuery1 + "\", NEW: \"" + xpathQuery + "\"");

            Object jdomNode = document; // Document, Element etc.
            //XPath path = new JDOMXPath("/*"); //--> das root element

            returnValue = xPath.selectNodes(jdomNode); // entries are from the type "org.jdom.Element"
        } catch (Throwable e) {
            e.printStackTrace();
        }

        return returnValue;
    }

    public static List<Element> xpathQuery(org.jdom.Document document, String xpathQuery1) {
        return xpathQuery(document, xpathQuery1, null);
    }

    /**
     * attention: the parent of the element is detached when no cloning
     *
     * @param aElement
     * @param xpathQuery
     * @param doClone
     * @return
     */
    public static List<Element> xpathQuery(org.jdom.Element aElement, String xpathQuery, boolean doClone) {
        List<Element> returnValue = new ArrayList<Element>();

        try {
            //Document parentDocument;
            //parentDocument = aElement.getDocument();

            Document document;
            Document oldDocument = null;
            if (doClone) {
                Element clone = (Element) aElement.clone();
                document = new Document(clone);
            } else {
                oldDocument = aElement.getDocument();
                aElement.detach();
                document = new Document(aElement);
            }
            returnValue = xpathQuery(document, xpathQuery);


        } catch (Exception e) {
            cat.error(e);
        }

        return returnValue;
    }

    // just some test stuff for the jaxen xpath library
/*
    public static void testJaxen() {
        try {
            org.jdom.Element root = new org.jdom.Element("root");
            org.jdom.Element child = new org.jdom.Element("child");
            child.setText("Ich bin ein Child");
            root.addContent(child);
            //org.jdom.Document doc1 = new org.jdom.Document(root);

            org.jdom.Document doc = XmlTools.readFromFile(Settings.getConfigFile(), null);

            org.jdom.Element e = doc.getRootElement();
            Object jdomNode = e; // Document, Element etc.
*/
    //XPath path = new JDOMXPath("/*"); //--> das root element
    //XPath path = new JDOMXPath("/imbConfig/mmdbConnection/*/host");
/*
            List results = path.selectNodes(jdomNode);
            System.out.println("Test: \"" + documentToString(e) + "\"");
            System.out.println("Results: " + results.size());

            Iterator it = results.iterator();
            while (it.hasNext()) {
                org.jdom.Element elem = (org.jdom.Element) it.next();
                System.out.println(elem.getName() + ", " + elem.getText());
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
*/
    public void xml2Pdf(org.jdom.Document document, OutputStream out) {
        /*Templates template;
        TransformerFactory tFactory = TransformerFactory.newInstance();

        XMLFilter xmlFilter = ((SAXTransformerFactory) tFactory).newXMLFilter(template);
        xmlFilter.setParent(XMLReaderFactory.createXMLReader());

        Driver driver = new Driver();
        driver.setRenderer(driver.RENDER_PDF);
        driver.setOutputStream(out);
        driver.render(xmlFilter, (new JDOMSource(document)).getInputSource());
        driver.reset();*/
    }

    private static void goRecursive(Element startElement, String namespaceName, Namespace nameSpace, Namespace newNamespace) {
        startElement.removeNamespaceDeclaration(nameSpace);
        startElement.setNamespace(newNamespace);

        List aList = startElement.getAttributes();
        for (int i = 0; i < aList.size(); i++) {
            Attribute a = (Attribute) aList.get(i);
            //System.out.println("N: " + a.getName());
            //if (a.getName().equalsIgnoreCase("type")) {
            //    System.out.println("NN: " + a.getName());
            //}

            String prefix = namespaceName + ":";
            String value = a.getValue();
            if (value.startsWith(prefix)) {
                a.setValue(value.substring(prefix.length()));
            }
        }

        List childList = startElement.getChildren();
        for (int i = 0; i < childList.size(); i++) {
            org.jdom.Element element = (org.jdom.Element) childList.get(i);
            goRecursive(element, namespaceName, nameSpace, newNamespace);
        }
    }

    /**
     * Remove all tag element prefixes, eg. "<mpeg7:Mpeg7>" -> "<Mpeg7>"
     *
     * @param doc
     */
    public static void removeAllNamespacesRecursive(org.jdom.Element doc) {
        if (doc == null) {
            return;
        }

        doc.setNamespace(null);

        /*
        console.echo("Prefix: \"" + namespace.getPrefix() + "\", URI: \"" + namespace.getURI() +
                    "\", toString: \"" + namespace.toString() + "\"");

        console.echo("additional:");
        for (int i = 0; i < docList.size(); i++) {
            namespace = (Namespace) docList.get(i);
            console.echo("Prefix: \"" + namespace.getPrefix() + "\", URI: \"" + namespace.getURI() +
                    "\", toString: \"" + namespace.toString() + "\"");
        }
        */


        List childList = doc.getChildren();
        for (int i = 0; i < childList.size(); i++) {
            org.jdom.Element element = (org.jdom.Element) childList.get(i);
            removeAllNamespacesRecursive(element);
        }
    }

    /**
     * Remove all tag element prefixes, eg. "<mpeg7:Mpeg7>" -> "<Mpeg7>"
     *
     * @param doc
     */
    public static void removeAllNamespacePrefix(org.jdom.Element doc) {
        if (doc == null) {
            return;
        }

        //Element rootElement = doc.getRootElement();
        org.jdom.Element rootElement = doc;
        String prefix = rootElement.getNamespacePrefix();

        if (prefix == null || prefix.length() < 1) {
            return;
        }

        //Namespace mpeg7Namespace = Mpeg7Template.getMpeg7Namespace();
        //Namespace mpeg7Mpeg7Namespace = Namespace.getNamespace("mpeg7", "urn:mpeg:mpeg7:schema:2001");

        Namespace newNameSpace = Namespace.getNamespace("", "urn:mpeg:mpeg7:schema:2001");

        Namespace namespace = Namespace.getNamespace(prefix);
        goRecursive(rootElement, prefix, namespace, newNameSpace);
    }

    /**
     * detaches the node from the docuemnt and make a new document from it
     *
     * @param node
     * @return
     */
    public static Document getNewDocumentFromElement(Element node) {
        Content c = node.detach();
        java.util.List l = new ArrayList();
        l.add(c);
        Document d = new Document(l);
        return d;
    }

    /**
     * returns the text of the element the xpath points to. if the element does not exist, defaultValue is returned
     *
     * @param element      the base element. e.g. new Element("root").add(..);
     * @param xPath        e.g. "root/person/firstname"
     * @param defaultValue "no first name given"
     * @return
     */
    public static String getXmlText(Element element, String xPath, String defaultValue) {
        String returnValue = defaultValue;

        try {
            Element elem = simpleXpath(element, xPath, null, false);
            if (elem != null && elem.getText() != null) {
                returnValue = elem.getText();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnValue;
    }

    public static Document readFromFile(InputStream stream, Document defaultDocument) {
        Document returnValue = null;
        try {
            SAXBuilder builder = new SAXBuilder();
            //File file = new File(new URI(fileName));
            cat.debug("READ: " + stream);
            //File file = new File(FileTools.removeFileUrlPrefix(fileName));
            returnValue = builder.build(stream);
        } catch (Exception je) {
            console.error("ERROR while reading stream \"" + stream + "\"");
            je.printStackTrace();
            returnValue = defaultDocument;
        }
        return returnValue;
    }
}  // end class

⌨️ 快捷键说明

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