person.xml:(不带命名空间)
<?xml version="1.0" encoding="UTF-8"?>
<Persons>
<Person id="1">
<Name>张三</Name>
<Age>120</Age>
</Person>
<Person id="2">
<Name>李四</Name>
<Age>20</Age>
</Person>
</Persons>
person.xsd:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:annotation>
<xs:documentation> 本文档定义Persons.xml的格式 </xs:documentation>
</xs:annotation>
<xs:element name="Persons">
<xs:complexType>
<xs:sequence>
<xs:element name="Person" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="Name">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="2" />
<xs:maxLength value="4" />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Age">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[1-9][0-9]?|1[01][0-9]|120" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
<xs:attribute name="id" use="required">
<xs:simpleType>
<xs:restriction base="xs:int"></xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
验证方法:
/// <summary>
/// 通过xsd验证xml格式是否正确,正确返回空字符串,错误返回提示
/// </summary>
/// <param name="xmlFile">xml文件</param>
/// <param name="xsdFile">xsd文件</param>
/// <param name="namespaceUrl">命名空间,无则默认为null</param>
/// <returns></returns>
public static string XmlValidationByXsd(string xmlFile, string xsdFile, string namespaceUrl = null)
{
StringBuilder sb = new StringBuilder();
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(namespaceUrl, xsdFile);
//验证出错时执行
settings.ValidationEventHandler += (x, y) =>
{
sb.AppendFormat("{0}|", y.Message);
};
using (XmlReader reader = XmlReader.Create(xmlFile, settings))
{
try
{
while (reader.Read()) ;
}
catch (XmlException ex)
{
sb.AppendFormat("{0}|",ex.Message);
}
}
return sb.ToString();
}
上面代码是验证xml文件,如果是xml字符串,则可用下面:
/// <summary>
/// 通过xsd验证xml格式是否正确,正确返回空字符串,错误返回提示
/// </summary>
/// <param name="xmlText">xml文本内容</param>
/// <param name="schemaFile">xsd文件</param>
/// <returns></returns>
public static string XmlValidateByXsd(string xmlText, string schemaFile)
{
StringBuilder sb = new StringBuilder();
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null, schemaFile);
settings.ValidationEventHandler += (x, y) =>
{
sb.AppendFormat("{0}\n", y.Message);
};
using (XmlReader reader = XmlReader.Create(new StringReader(xmlText), settings))
{
try
{
while (reader.Read()) ;
}
catch (XmlException ex)
{
sb.AppendFormat("{0}\n", ex.Message);
}
}
return sb.ToString();
}
https://msdn.microsoft.com/en-us/library/system.xml.xmldocument(v=vs.110).aspx