我正在尝试反序列化我从第三方Web服务中提取的XML文档,而该文档是我无法控制的,它们只将数据作为XML发送 - 它看起来如下所示:
<?xml version="1.0" encoding="utf-8"?>
<GameArray xmlns="http://foo.bar">
<Game>
<Id>int</Id>
<Title>string</Title>
</Game>
<Game>
<Id>int</Id>
<Title>string</Title>
</Game>
</GameArray>
我的班级看起来像这样:
public class GamesModel
{
[XmlArray("GameArray")]
[XmlArrayItem("Game")]
public List<Game> GameList { get; set; }
public GamesModel ToXml()
{
var request =
WebRequest.Create(
"http://foo.bar/GetGames") as
HttpWebRequest;
var xRoot = new XmlRootAttribute
{
ElementName = "GameArray",
Namespace = "http://foo.bar",
IsNullable = true
};
var ser = new XmlSerializer(typeof(GamesModel), xRoot);
var response = request.GetResponse();
var result = ser.Deserialize(response.GetResponseStream());
return (GamesModel)result;
}
}
public class Game
{
[XmlElement("Id")]
public int Id { get; set; }
[XmlElement("Title")]
public string Title{ get; set; }
}
在我的控制器中,我有这个设置:
[HttpGet]
public ActionResult GetGames()
{
var xboxGames = new GamesModel();
return Content(GamesModel.ToXml().ToString(), "text/xml");
}
然后在我看来我有一些带有按钮的HTML,我希望它在click事件中调用它 - 所以我的jquery看起来像这样
$('.testTag').click(function() {
$.ajax({
type: "GET",
url: "/Home/GetGames",
dataType: "xml/text",
success: function(xml) {
//dostuff
}
});
});
我在所有这些上都很好地点击了服务器,但是在我要解密的行上出错了。错误是:
{"There is an error in XML document (2, 2)."}
InnerException是:
{"<GameArray xmlns='http://foo.bar/'> was not expected."}
我一直在试着弄几个小时试图找出我需要做的事情。
答案 0 :(得分:2)
您的xml序列化程序需要有关根元素和 xml命名空间的一些帮助。
XmlSerializer ser = new XmlSerializer(typeof(Game[]),
new XmlRootAttribute("GameArray") { Namespace = "http://foo.bar" });
var games = (Game[])ser.Deserialize(stream);
public class Game
{
public string Id { set; get; }
public string Title { set; get; }
}
修改强>
string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<GameArray xmlns=""http://foo.bar"">
<Game>
<Id>int</Id>
<Title>string</Title>
</Game>
<Game>
<Id>int</Id>
<Title>string</Title>
</Game>
</GameArray>";
XmlSerializer ser = new XmlSerializer(typeof(Game[]),
new XmlRootAttribute("GameArray") { Namespace = "http://foo.bar" });
var games = (Game[])ser.Deserialize(new StringReader(xml));