您好,登錄后才能下訂單哦!
xml是常用的一種數(shù)據(jù)文件格式,它的定義文件為Xml schema definition(XSD),那么怎么驗(yàn)證一個(gè)xml是否符合它的schema定義呢?
本文給出C#的代碼實(shí)現(xiàn)。
存儲(chǔ)在xml.xml文件中
<?xml version="1.0" encoding="utf-8" ?>
<xml>
<age>10</age>
<date>2018-01-01</date>
<regex>111</regex>
<gMonth>---10--</gMonth>
<language>english</language>
<anyURI>./news.html</anyURI>
</xml>
存儲(chǔ)在xsd.xsd文件中
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="xml">
<xs:complexType>
<xs:sequence>
<xs:element name="age">
<xs:simpleType>
<xs:restriction base="xs:decimal">
<xs:enumeration value="10"/>
<xs:enumeration value="20"/>
<xs:enumeration value="30"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="date">
<xs:simpleType>
<xs:restriction base="xs:date">
<xs:enumeration value="2018-01-01Z"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="regex">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[0-9][0-9][0-9]"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="gMonth" type="xs:gMonth"/>
<xs:element name="language" type="xs:language"/>
<xs:element name="anyURI" type="xs:anyURI"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
下面代碼在Console Project中實(shí)現(xiàn)
class Program
{
static void Main(string[] args)
{
string xmlFile = "xml.xml";
string xsdFile = "xsd.xsd";
var exceptionMessage = string.Empty;
VerifyXML(xsdFile, xmlFile, ref exceptionMessage);
Console.WriteLine(exceptionMessage);
Console.ReadKey();
}
private static void VerifyXML(string xsdFile, string xmlFile, ref string exceptionMessage)
{
XmlDocument doc = LoadXML(xmlFile);
doc.Schemas = LoadXMLSchmeaFromXSDFile(xsdFile);
string errorMessage = string.Empty;
ValidationEventHandler eventHandler = new ValidationEventHandler(delegate (object sender, ValidationEventArgs e)
{
switch (e.Severity)
{
case XmlSeverityType.Error:
errorMessage += e.Message;
break;
case XmlSeverityType.Warning:
break;
}
});
doc.Validate(eventHandler);
exceptionMessage = errorMessage;
}
private static XmlDocument LoadXML(string xmlFile)
{
XmlDocument doc = new XmlDocument();
doc.Load(xmlFile);
return doc;
}
private static XmlSchemaSet LoadXMLSchmeaFromXSDFile(string path)
{
var schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(path));
return schemas;
}
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。