簡體   English   中英

驗證Xml,Xsd並轉換為其他Xml

[英]Validating Xml, Xsd and transform to other Xml

我試圖在Java中輸入xml,xsd並對其進行驗證。 接下來,如果我發現它們為true,則必須將輸入xml轉換為其他xml。 我已經以某種方式完成了程序,盡管xml和xsd都沒有驗證正確...我可以使用我不想使用的xsl將xml轉換為其他xml。 需要幫助。

代碼如下:在此代碼中,XsdFile和XslFile均已預定義到我要測試的文件夾中。 它們只是對象。 或者,像文件“ c:\\ abc.xml”那樣思考。 我只關心條件if(doc!= null) 我應該給那里做些什么。 盡管驗證失敗,但以下代碼仍在工作。

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();
    }

有點煩人。 用於XML解析的默認ErrorHandler只會打印出錯誤。 因此,當驗證失敗時,您只會收到一條錯誤消息。 您應該在DocumentBuilderFactory上指定一個自定義ErrorHandler,當驗證失敗時會引發異常。

附帶說明,由於您已經將xml解析為DOM,因此應使用DOMSource進行轉換(因此,無需重新解析xml即可對其進行轉換)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM