【问题标题】:Missing schema errors when using an Xsd to validate Xml from a serialized WCF Proxy class使用 Xsd 从序列化 WCF 代理类验证 Xml 时缺少架构错误
【发布时间】:2012-12-12 15:02:45
【问题描述】:

我正在尝试使用 Xsd 验证序列化的 WCF 代理类。

我注意到生成的 Xml 不包括父元素上的命名空间,但子元素有它。这意味着我的验证会抛出找不到元素的架构信息类型错误。

如果我手动添加默认命名空间,则架构验证有效。

我的问题是,如果请求对象具有命名空间的序列化属性,为什么不自动生成呢?

这就是我为代理生成序列化 Xml 的方式:

var path = @"C:\DataRequest.xml";
var data = new DataRequest(); 
using (var fileWriter = new StreamWriter(path))
{
   var serializer = new XmlSerializer(data.GetType());
   serializer.Serialize(fileWriter, data);
   fileWriter.Close();
}

这会产生以下 DataRequest.xml:

<DataRequest>
  <Data xmlns="urn:some:name:space">
    <Id>1</Id>
  </Data>
</DataRequest>

这是我的带有命名空间序列化属性的请求对象:

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.17929")]
<other attributes I snipped>
[System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:some:name:space")]
public partial class DataRequest : object, System.ComponentModel.INotifyPropertyChanged {

【问题讨论】:

    标签: c# .net wcf xml-serialization


    【解决方案1】:

    我发现在使用 XmlSerializer 时,要获取根目录下的命名空间,需要将XmlRootAttribute 应用于目标类。

    【讨论】:

    • 我的代理类是通过 wsdl 自动生成的?
    【解决方案2】:

    我通过在序列化时动态获取命名空间值解决了这个问题。

    这是修改后的函数:

    var dataType = data.GetType();
    var xmlAttribute = (XmlTypeAttribute)Attribute.GetCustomAttribute(dataType, typeof(XmlTypeAttribute));
    XNamespace ns = xmlAttribute.Namespace;
    using (var fileWriter = new StreamWriter(filePath))
    {
       var xSerializer = new XmlSerializer(dataType, ns.NamespaceName);
       xSerializer.Serialize(fileWriter, data);
       fileWriter.Close();    
    }
    


    代码来自这个 SO 答案:
    How can I dynamically read a classes XmlTypeAttribute to get the Namespace?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 2012-06-04
      • 2018-04-17
      相关资源
      最近更新 更多