0
我試圖在java中輸入xml,xsd並驗證它們。接下來,如果我發現它們是真的,那麼我必須將輸入xml轉換爲其他xml。我已經完成了我的程序,雖然xml和xsd不驗證真實...我可以使用xsl將xml轉換爲其他xml,我不想這樣做。需要幫助。驗證Xml,Xsd並轉換爲其他Xml
代碼如下:在此代碼中,XsdFile,XslFile都是預定義的文件夾,我想測試。他們只是對象。另一種方法是像文件「c:\ abc.xml」一樣思考。如果(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();
}