如何使用XSD生成的c#类验证XML

时间:2015-04-20 13:50:17

标签: c# xml xsd linq-to-xml xml-validation

我想从客户端向本地服务器发送http请求,在服务器上我使用Linq查询,返回xml中的数据 我也有.xsd文件和从我的xsd文件中加入的.cs文件,我要用它来验证我的xml。 我有几个问题:

  • 如何使用c#生成的类验证xml?
  • 如何将xml从服务器返回到客户端?

http://www.codeproject.com/Questions/898525/How-to-validate-XML-with-generated-csharp-class-fr 感谢

1 个答案:

答案 0 :(得分:2)

好吧,我看到两个单独的问题,所以我将提供两个单独的答案:

1.。如何验证XML [使用C#生成的类]

答案实际上根本不涉及C#生成的类。一旦验证了XML,就可以将其反序列化为自动生成的类;但是,根据模式验证XML不需要它。要根据已知模式验证XML(假设您有XSD文件),可以执行以下操作:

// define your schema set by importing your schema from an xsd file
var schemaSet = new XmlSchemaSet();
var schema = XmlReader.Create("D:\myschema.xsd");
schemaSet.Add(null, schema);
schemaSet.Compile();

// your schema defines several types. Your incoming XML is (presumably) expected to of one of these types (e.g. type="_flashList")
// whatever the expected type is of the XML document root, use that string here to grab information about that type from the schema
var partialSchemaObject = schemaSet.GlobalTypes[new XmlQualifiedName("_flashList")];

// go get your xml, then validate!
// here, SchemaValidationEventHandler is a delegate that is called for every validation error or warning
var myXml = GoGetMyXmlIWantToValidate() as XDocument;
myXml.Root.Validate(partialSchemaObject, schemaSet, SchemaValidationEventHandler, true);

2.。如何将XML从服务器返回到客户端?

您可以为HttpContent

使用'StringContent'类型
var myResponseXml = GoGetMyResponseXml() as XElement;
var response = new HttpResponseMessage(HttpStatusCode.OK)
               {
                   // specify string content, with UTF8 encoding, with a content-type of application/xml
                   Content = new StringContent(myResponseXml.ToString(), Encoding.UTF8, "application/xml");
               };