很多时候我们的应用程序或者web程序需要用到xml文件进行配置,而最终的程序是需要给客户使用的,所以xml或者也需要客户来写,而客户来写的话的,就不能保证xml文件绝对的正确,于是我写了这个类,主要功能就是验证xml书写文件是否符合定义的xsd规范.
package
common.xml.validator;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.IOException;
import
java.io.InputStream;
import
java.io.Reader;
import
java.io.StringReader;
import
java.net.URL;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
import
javax.xml.XMLConstants;
import
javax.xml.transform.Source;
import
javax.xml.transform.stream.StreamSource;
import
javax.xml.validation.Schema;
import
javax.xml.validation.SchemaFactory;
import
javax.xml.validation.Validator;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
import
org.xml.sax.SAXException;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
/** */
/**
* @author suyuan
*
*/
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
public
class
XmlSchemaValidator
{
private boolean isValid = true;
private String xmlErr = "";
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public boolean isValid()
{
return isValid;
}
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public String getXmlErr()
{
return xmlErr;
}
public XmlSchemaValidator()
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
}
public boolean ValidXmlDoc(String xml,URL schema)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
StringReader reader = new StringReader(xml);
return ValidXmlDoc(reader,schema);
}
public boolean ValidXmlDoc(Reader xml,URL schema)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
try
{
InputStream schemaStream = schema.openStream();
Source xmlSource = new StreamSource(xml);
Source schemaSource = new StreamSource(schemaStream);
return ValidXmlDoc(xmlSource,schemaSource);
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
} catch (IOException e)
{
isValid = false;
xmlErr = e.getMessage();
return false;
}
}
public boolean ValidXmlDoc(String xml,File schema)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
StringReader reader = new StringReader(xml);
return ValidXmlDoc(reader,schema);
}
public boolean ValidXmlDoc(Reader xml,File schema)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
try
{
FileInputStream schemaStream = new FileInputStream(schema);
Source xmlSource = new StreamSource(xml);
Source schemaSource = new StreamSource(schemaStream);
return ValidXmlDoc(xmlSource,schemaSource);
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
} catch (IOException e)
{
isValid = false;
xmlErr = e.getMessage();
return false;
}
}
public boolean ValidXmlDoc(Source xml,Source schemaSource)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
try
{ SchemaFactory schemafactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
if(xml==null||xml.equals(""))
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return false;
}
Schema schema = schemafactory.newSchema(schemaSource);
Validator valid = schema.newValidator();
valid.validate(xml);
return true;
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
} catch (SAXException e)
{
isValid = false;
xmlErr = e.getMessage();
return false;
}
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
catch (IOException e)
{
isValid = false;
xmlErr = e.getMessage();
return false;
}
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
catch (Exception e)
{
isValid = false;
xmlErr = e.getMessage();
return false;
}
}
}
类的使用方法如下:
package
common.xml.validator;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
import
java.io.
*
;
import
java.net.URL;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
public
class
testXmlValidator
{
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/** *//**
* @param args
*/
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public static void main(String[] args)
{
InputStream XmlStream = testXmlValidator.class.getResourceAsStream("test.xml");
Reader XmlReader = new InputStreamReader(XmlStream);
URL schema =testXmlValidator.class.getResource("valid.xsd");
XmlSchemaValidator xmlvalid = new XmlSchemaValidator();
System.out.println(xmlvalid.ValidXmlDoc(XmlReader, schema));
System.out.print(xmlvalid.getXmlErr());
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
}
xsd文件定义如下:
被验证的xml 实例如下:
<?
xml version="1.0" encoding="utf-8"
?>
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
<
Answer
>
<
ShortDesc
>
385
</
ShortDesc
>
<
AnswerValue
>
1
</
AnswerValue
>
</
Answer
>
这个是java版本的类,C# 的类文件如下(是一个老美写的,我的类是根据他的类翻译过来的):
using
System;
using
System.Xml;
using
System.Xml.Schema;
using
System.IO;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
namespace
ProtocolManager.WebApp
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// This class validates an xml string or xml document against an xml schema.
/// It has public methods that return a boolean value depending on the validation
/// of the xml.
/// </summary>
public class XmlSchemaValidator
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
private bool isValidXml = true;
private string validationError = "";
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// Empty Constructor.
/// </summary>
public XmlSchemaValidator()
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// Public get/set access to the validation error.
/// </summary>
public String ValidationError
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
get
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return "<ValidationError>" + this.validationError + "</ValidationError>";
}
set
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
this.validationError = value;
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// Public get access to the isValidXml attribute.
/// </summary>
public bool IsValidXml
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
get
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return this.isValidXml;
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// This method is invoked when the XML does not match
/// the XML Schema.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void ValidationCallBack(object sender, ValidationEventArgs args)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// The xml does not match the schema.
isValidXml = false;
this.ValidationError = args.Message;
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// This method validates an xml string against an xml schema.
/// </summary>
/// <param name="xml">XML string</param>
/// <param name="schemaNamespace">XML Schema Namespace</param>
/// <param name="schemaUri">XML Schema Uri</param>
/// <returns>bool</returns>
public bool ValidXmlDoc(string xml, string schemaNamespace, string schemaUri)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
try
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// Is the xml string valid?
if(xml == null || xml.Length < 1)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return false;
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
StringReader srXml = new StringReader(xml);
return ValidXmlDoc(srXml, schemaNamespace, schemaUri);
}
catch(Exception ex)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
this.ValidationError = ex.Message;
return false;
}
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// This method validates an xml document against an xml schema.
/// </summary>
/// <param name="xml">XmlDocument</param>
/// <param name="schemaNamespace">XML Schema Namespace</param>
/// <param name="schemaUri">XML Schema Uri</param>
/// <returns>bool</returns>
public bool ValidXmlDoc(XmlDocument xml, string schemaNamespace, string schemaUri)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
try
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// Is the xml object valid?
if(xml == null)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return false;
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
// Create a new string writer.
StringWriter sw = new StringWriter();
// Set the string writer as the text writer to write to.
XmlTextWriter xw = new XmlTextWriter(sw);
// Write to the text writer.
xml.WriteTo(xw);
// Get
string strXml = sw.ToString();
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
StringReader srXml = new StringReader(strXml);
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
return ValidXmlDoc(srXml, schemaNamespace, schemaUri);
}
catch(Exception ex)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
this.ValidationError = ex.Message;
return false;
}
}
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// This method validates an xml string against an xml schema.
/// </summary>
/// <param name="xml">StringReader containing xml</param>
/// <param name="schemaNamespace">XML Schema Namespace</param>
/// <param name="schemaUri">XML Schema Uri</param>
/// <returns>bool</returns>
public bool ValidXmlDoc(StringReader xml, string schemaNamespace, string schemaUri)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// Continue?
if(xml == null || schemaNamespace == null || schemaUri == null)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return false;
}
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
isValidXml = true;
XmlValidatingReader vr;
XmlTextReader tr;
XmlSchemaCollection schemaCol = new XmlSchemaCollection();
schemaCol.Add(schemaNamespace, schemaUri);
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
try
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// Read the xml.
tr = new XmlTextReader(xml);
// Create the validator.
vr = new XmlValidatingReader(tr);
// Set the validation tyep.
vr.ValidationType = ValidationType.Auto;
// Add the schema.
if(schemaCol != null)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
vr.Schemas.Add(schemaCol);
}
// Set the validation event handler.
vr.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
// Read the xml schema.
while(vr.Read())
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
}
vr.Close();
return isValidXml;
}
catch(Exception ex)
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
this.ValidationError = ex.Message;
return false;
}
finally
![ExpandedSubBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
// Clean up![](https://www.cnblogs.com/Images/dot.gif)
vr = null;
tr = null;
}
}
}
}
希望 以上类对大家有所帮助,当然我也是在这里做一个标记,以后有需要可以直接用了 呵呵