简体   繁体   English

XML反序列化仅适用于xml中的命名空间

[英]XML deserializing only works with namespace in xml

The most simple way I get ServiceStack xml deserialization to work is when the xml contains a namespace. 使ServiceStack xml反序列化工作的最简单方法是xml包含命名空间。 However, the xml I receive do not contain namespaces. 但是,我收到的xml不包含名称空间。 The most simple working example: 最简单的工作示例:

[Serializable]
public class test
{

}

class Program
{
   static void Main(string[] args)
   {
       string xml="<test xmlns=\"http://schemas.datacontract.org/2004/07/\"></test>";
       var result = ServiceStack.Text.XmlSerializer.DeserializeFromString<test>(xml);
   }
}

However, that is not what I want. 但是,这不是我想要的。 I want the following to deserialize, since that is the xml I get from several services: 我希望以下代码反序列化,因为这是我从几个服务获得的xml:

string xml="<test></test>";

But that gives me the following error: 但是这给了我以下错误:

DeserializeDataContract: Error converting type: Error in line 1 position 7. 
Expecting element 'test' from namespace 
'http://schemas.datacontract.org/2004/07/'.. 
Encountered 'Element'  with name 'test', namespace ''.

I tried: 我试过了:

[Serializable]
[XmlRoot("test", Namespace = "")]
public class test

I can't create a new Serializer, because ServiceStack.Text.XmlSerializer is static. 我无法创建新的Serializer,因为ServiceStack.Text.XmlSerializer是静态的。 I need to choose for either Microsoft XmlSerializer OR ServiceStack (not both). 我需要选择Microsoft XmlSerializer或ServiceStack(不是两者)。 Meaning: if I can't get this simple example to work I need to skip an otherwise very useful part of the ServiceStack package. 含义:如果我不能让这个简单的例子工作,我需要跳过ServiceStack包中另一个非常有用的部分。 The last thing I want is to inject some dummy namespace in the incoming xml. 我想要的最后一件事是在传入的xml中注入一些虚拟命名空间。

ServiceStack uses .NET's Xml DataContractSerializer to serialize XML to remove Namespaces you need to either set the Namespace to an empty string with: ServiceStack使用.NET的Xml DataContractSerializer序列化XML以删除命名空间,您需要将命名空间设置为空字符串:

[DataContract(Namespace="")]
public class test { ... }

But then you'll have to mark each property you want serialized with [DataMember] attributes. 但是,您必须使用[DataMember]属性标记要序列化的每个属性。 A better option is to specify an empty namespace for all types under a C# namespace by adding and Assembly attribute in your Assembly.cs file, eg: 更好的选择是通过在Assembly.cs文件中添加和Assembly属性为C#命名空间下的所有类型指定一个空命名空间,例如:

[assembly: ContractNamespace("", ClrNamespace = "MyServiceModel.DtoTypes")]

Note: you can remove the [Serializable] attribute - it's not used by any of ServiceStack's serializers. 注意:您可以删除[Serializable]属性 - 任何ServiceStack的序列化程序都不会使用它。 Also all XmlSerializer attributes like [XmlRoot] are useless since ServiceStack uses .NET's DataContractSerializer not Microsoft's earlier XmlSerializer. 此外,像[XmlRoot]这样的所有XmlSerializer属性都是无用的,因为ServiceStack使用的是.NET的DataContractSerializer,而不是微软早期的XmlSerializer。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM