xsd操作

1.xsd介绍
详见: http://blog.sina.com.cn/s/blog_ad0672d60102uy6w.html
2.生成xsd
DataSet dataSet = new DataDet();
// read date from xml file
dataSet.ReadXml(@"xml2.xml", XmlReadMode.ReadSchema);
// .. or set data with code
// save as xsd file
System.IO.StreamWriter writer = new System.IO.StreamWriter("Customers.xsd");
dataSet.WriteXmlSchema(writer);
writer.Close();
// get xsd format contents
string schemaString = dataSet.GetXmlSchema();
// save as xml
dataSet.WriteXml(@"xml2_new.xml", XmlWriteMode.WriteSchema);
3.由xsd生成xml
xsd.exe工具可生成操作的cs类,再有生成的cs类生成xml文件
详见: http://blog.sina.com.cn/s/blog_ad0672d60101g02h.html
4.xsd检验xml
using System.Xml;        // for XmlTextReader and XmlValidatingReader
using System.Xml.Schema; // for XmlSchemaCollection (which is used later)
private static bool isValid = true;      // If a validation error occurs,
                                         // set this flag to false in the
                                         // validation event handler. 
XmlTextReader r = new XmlTextReader("ProductWithXSD.xml");
XmlValidatingReader v = new XmlValidatingReader(r);
v.ValidationType = ValidationType.Schema;
v.ValidationEventHandler += new ValidationEventHandler(MyValidationEventHandler);
while (v.Read())
{
   // Can add code here to process the content.
}
v.Close();
// Check whether the document is valid or invalid.
if (isValid)
   Console.WriteLine("Document is valid");
else
   Console.WriteLine("Document is invalid");
   
public static void MyValidationEventHandler(object sender, 
                                            ValidationEventArgs args) 
{
   isValid = false;
   Console.WriteLine("Validation event\n" + args.Message);
}
// 另一种方法
XDocument xDoc = XDocument.Parse(xxxxxxx);
string xsdPath = ConfigUtils.GetXsdPath(XsdSchemaIdentifier.HHDataItem);
XmlSchemaSet xss = new XmlSchemaSet();
xss.Add("", xsdPath);
fs.Close();
fs.Dispose();
xDoc.Validate(xss, null);

你可能感兴趣的:(xsd操作)