我正在使用C#并且有关于对XML字符串进行反序列化的问题。
这是我要序列化的代码:
public object XmlDeserializeFromString(string objectData, Type type)
{
var serializer = new XmlSerializer(type);
object result;
using (TextReader reader = new StringReader(objectData))
{
result = serializer.Deserialize(reader);
}
return result;
}
以下XML适用于上述功能:
<House>
<address>21 My House</address>
<id>1</id>
<owner>Optimation</owner>
</House>
但是,我的Web API应用程序中的XML不会:
<House xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MVCwithWebAPIApplication.Models">
<address>21 My House</address>
<id>1</id>
<owner>Optimation</owner>
</House>
如何从我的Web API应用程序中获取XmlDeserializeFromString
函数以使用XML?
答案 0 :(得分:1)
来自web api的xml返回内部有一个默认命名空间。要将此xml反序列化为内存对象(由c#类定义),XmlSerialize必须知道该类是否属于该命名空间。这由附加到该类的RootAttribute中的属性“Namespace”指定。如果xml中的命名空间与c#类中声明的命名空间匹配,则xml成功反序列化。否则反序列化失败。
有关xml命名空间的更多信息,请参阅http://www.w3schools.com/xml/xml_namespaces.asp
下面是演示解决方案供您参考。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
namespace ConsoleApplication8 {
class Program {
static void Main(string[] args) {
var s1 = "<House><address>21 My House</address><id>1</id><owner>Optimation</owner></House>";
var s2 = "<House xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/MVCwithWebAPIApplication.Models\"><address>21 My House</address><id>1</id><owner>Optimation</owner></House>";
House house = (House)XmlDeserializeFromString(s2, typeof(House));
Console.WriteLine(house.ToString());
Console.Read();
}
public static Object XmlDeserializeFromString(string objectData, Type type) {
var serializer = new XmlSerializer(type);
object result;
using (TextReader reader = new StringReader(objectData)) {
result = serializer.Deserialize(reader);
}
return result;
}
}
//this is the only change
[XmlRoot(Namespace="http://schemas.datacontract.org/2004/07/MVCwithWebAPIApplication.Models")]
public class House {
public String address { get; set; }
public String id { get; set; }
public String owner { get; set; }
public override string ToString() {
return String.Format("address: {0} id: {1} owner: {2}", address, id, owner);
}
}
}