XML反序列化只适用于在XML命名空间 [英] XML deserializing only works with namespace in xml
问题描述
最简单的方法,我得到ServiceStack XML序列化工作是当XML包含一个名称空间。然而,XML我收到不包含命名空间。最简单的例子:
The most simple way I get ServiceStack xml deserialization to work is when the xml contains a namespace. However, the xml I receive do not contain namespaces. 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);
}
}
不过,这不是我想要的。我想下面的反序列化,因为这是XML我从几个服务获得:
However, that is not what I want. I want the following to deserialize, since that is the xml I get from several services:
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
我不能创建一个新的串行器,因为ServiceStack.Text.XmlSerializer是静态的。我需要选择的是Microsoft的XmlSerializer或ServiceStack(不能同时)。含义:如果我不能得到这个简单的例子来工作,我需要跳过ServiceStack包的,否则非常有用的部分。我想的最后一件事是注入XML中的一些虚拟的命名空间。
I can't create a new Serializer, because ServiceStack.Text.XmlSerializer is static. I need to choose for either Microsoft XmlSerializer OR ServiceStack (not both). Meaning: if I can't get this simple example to work I need to skip an otherwise very useful part of the ServiceStack package. The last thing I want is to inject some dummy namespace in the incoming xml.
推荐答案
ServiceStack使用.NET的XML DataContractSerializer的序列化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:
[DataContract(Namespace="")]
public class test { ... }
不过,那么你就必须标记每个属性你要系列化[DataMember]标注属性。更好的选择是通过添加和在 Assembly.cs 文件Assembly特性,要指定一个C#命名空间下所有类型的空白空间如:
But then you'll have to mark each property you want serialized with [DataMember] attributes. 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, e.g:
[assembly: ContractNamespace("", ClrNamespace = "MyServiceModel.DtoTypes")]
请注意:您可以删除[Serializable]属性 - 它没有被任何ServiceStack的序列化。此外,各XmlSerializer的属性,如[XmlRoot]是无用的,因为ServiceStack使用.NET的DataContractSerializer的不是微软的早期XmlSerializer的。
Note: you can remove the [Serializable] attribute - it's not used by any of ServiceStack's serializers. Also all XmlSerializer attributes like [XmlRoot] are useless since ServiceStack uses .NET's DataContractSerializer not Microsoft's earlier XmlSerializer.
这篇关于XML反序列化只适用于在XML命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!