【问题标题】:How to validate XML with generated c# class from XSD如何使用从 XSD 生成的 c# 类验证 XML
【发布时间】:2015-06-27 07:00:29
【问题描述】:

我想从客户端向本地服务器发送一个 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 谢谢

【问题讨论】:

  • 您能否提供您的 XSD 文件的 sn-p,以便我可以更好地针对您的 XSD 定义类型定制我的答案?此外,SO 问题通常应该能够独立(不依赖链接来进一步定义问题)。能把codeproject.com上关于这个问题的相关信息带到这个问题上吗?

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


【解决方案1】:

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

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");
               };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多