Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

c# - 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. 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);
   }
}

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 { ... }

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")]

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...