好吧,我看到两个不同的问题,所以我将提供两个不同的答案:
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");
};