JBPM流程定义校验之java利用XSD校验XML
上篇我们学习了在.net中怎样利用XSD来验证xml,今天我们来看一下在java中怎样实现利用xsd来校验xml!
package
WFTH;
import java.io. * ;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation. * ;
import org.xml.sax.SAXException;
/**
* @author 无风听海
*
*/
public class ValidationManager {
public static String ValidationXmlByXSD(String filePath,String xsdPath,String nameSpace) throws SAXException, IOException {
String msg = filePath + " is valid. " ;
SchemaFactory factory = SchemaFactory.newInstance( " http://www.w3.org/2001/XMLSchema " );
Schema schema = null ;
// xml和xsd是独立的文件,否则是内联文件
if (xsdPath != null && xsdPath != "" ){
File schemaLocation = new File(xsdPath);
schema = factory.newSchema(schemaLocation);
}
else {
schema = factory.newSchema();
}
Validator validator = schema.newValidator();
Source source = new StreamSource(filePath);
try {
validator.validate(source);
}
catch (SAXException ex) {
msg = filePath + " is not valid because " + ex.getMessage();
}
return msg;
}
}
import java.io. * ;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation. * ;
import org.xml.sax.SAXException;
/**
* @author 无风听海
*
*/
public class ValidationManager {
public static String ValidationXmlByXSD(String filePath,String xsdPath,String nameSpace) throws SAXException, IOException {
String msg = filePath + " is valid. " ;
SchemaFactory factory = SchemaFactory.newInstance( " http://www.w3.org/2001/XMLSchema " );
Schema schema = null ;
// xml和xsd是独立的文件,否则是内联文件
if (xsdPath != null && xsdPath != "" ){
File schemaLocation = new File(xsdPath);
schema = factory.newSchema(schemaLocation);
}
else {
schema = factory.newSchema();
}
Validator validator = schema.newValidator();
Source source = new StreamSource(filePath);
try {
validator.validate(source);
}
catch (SAXException ex) {
msg = filePath + " is not valid because " + ex.getMessage();
}
return msg;
}
}
本文介绍了一种使用Java进行XML文件校验的方法,通过XSD(XML Schema Definition)来确保XML文件的有效性和规范性。文章提供了一个具体的示例代码,展示了如何创建一个验证管理器来验证XML文件是否符合指定的XSD模式。

358

被折叠的 条评论
为什么被折叠?



