简体   繁体   中英

Validating Xml, Xsd and transform to other Xml

I was trying to input an xml, xsd in java and validate them. Next if i found them true, then i have to transform the input xml to other xml. I have done my program in such a way that though the xml and xsd are not validating true... I could transform the xml to other xml using xsl which i dont want to. A help would be needed.

Code is below: Here in this code, XsdFile, XslFile all are predefined to the folder where i would like to test. They are just objects. alternative, to think like a file "c:\\abc.xml". I am only concerned at the condition if(doc!=null) . What should i give there to work fine. The following code is working though the validation fails.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setAttribute(
            "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
            "http://www.w3.org/2001/XMLSchema");
    factory
            .setAttribute(
                    "http://java.sun.com/xml/jaxp/properties/schemaSource",
                    XsdFile);

    try {
        System.out.println();
        DocumentBuilder parser = factory.newDocumentBuilder();
        Document doc = parser.parse(XmlFile);

        if (doc != null) {
            Source xmlInput = new StreamSource(new File(XmlFile));
            Source xsl = new StreamSource(new File(inputXslFile));
            Result xmlOutput = new StreamResult(new File(transformedXml));

            try {
                Transformer transformer = TransformerFactory.newInstance()
                        .newTransformer(xsl);
                transformer.transform(xmlInput, xmlOutput);
                System.out.println("The transformed xml is:" + xmlOutput);
            } catch (TransformerException e) {
                // Handle.
            }

        }

    } catch (ParserConfigurationException e) {
        System.out.println("Parser not configured: " + e.getMessage());
    } catch (SAXException e) {
        System.out.print("Parsing XML failed due to a "
                + e.getClass().getName() + ":");
        System.out.println(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
    }

It's kind of annoying. the default ErrorHandler for XML parsing just prints out the errors. So, when validation fails, you'll just get an error message. you should specify a custom ErrorHandler on the DocumentBuilderFactory which throws an exception when the validation fails.

as a side note, since you've already parsed the xml into DOM, you should use a DOMSource for your transformation (so you don't need to re-parse the xml in order to transform it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM