【问题标题】:Validating Xml, Xsd and transform to other Xml验证 Xml、Xsd 并转换为其他 Xml
【发布时间】:2012-08-31 17:04:13
【问题描述】:

我试图在 java 中输入一个 xml、xsd 并验证它们。接下来,如果我发现它们是真的,那么我必须将输入 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();
    }

【问题讨论】:

    标签: java javascript xml eclipse hibernate


    【解决方案1】:

    这有点烦人。 XML 解析的默认 ErrorHandler 只是打印出错误。因此,当验证失败时,您只会收到一条错误消息。您应该在 DocumentBuilderFactory 上指定一个自定义 ErrorHandler,它会在验证失败时引发异常。

    附带说明,由于您已经将 xml 解析为 DOM,因此您应该使用 DOMSource 进行转换(因此您无需重新解析 xml 即可对其进行转换)。

    【讨论】:

      猜你喜欢
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多