[英]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.