使用c#反序列化失败
本文关键字:失败 反序列化 使用 | 更新日期: 2023-09-27 18:25:21
我正在尝试反序列化这个xml:
<?xml version="1.0" encoding="UTF-8"?>
<query xmlns:yahoo="http://www.yahooapis.com/v1/base.rng"
yahoo:count="10" yahoo:created="2012-02-20T19:07:02Z" yahoo:lang="en-US">
<results>
<a href="/dir/index?sid=396545299">Books & Authors</a>
<a href="/dir/index?sid=396545374">Dancing</a>
<a href="/dir/index?sid=396546034">Genealogy</a>
<a href="/dir/index?sid=396545298">History</a>
<a href="/dir/index?sid=396545310">Other - Arts & Humanities</a>
<a href="/dir/index?sid=396545300">Performing Arts</a>
<a href="/dir/index?sid=396545231">Philosophy</a>
<a href="/dir/index?sid=2115500137">Poetry</a>
<a href="/dir/index?sid=396546419">Theater & Acting</a>
<a href="/dir/index?sid=396545309">Visual Arts</a>
</results>
</query>
这是雅虎api在查询类别和子类别时返回的xml。
这个代码应该反序列化它:
string query_string = "some_url";
HttpWebRequest request = HttpWebRequest.Create
(query_string) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
System.Xml.Serialization.XmlSerializer serializer = new
System.Xml.Serialization.XmlSerializer(typeof(queryA));
queryA Q = (queryA)serializer.Deserialize(reader); // THIS IS WHERE THE EXCEPTION IS THROWN
reader.Close();
}
我得到一个异常:XML文档(2,2)中有一个错误。
异常详细信息:
"<query xmlns=''> was not expected."
这是课程:
namespace Yahoo_answers_tool {
using System.Xml.Serialization;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class queryA {
private queryResultsA[] resultsField;
private string countField;
private string createdField;
private string langField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlArrayItemAttribute("a", typeof(queryResultsA), Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public queryResultsA[] results {
get {
return this.resultsField;
}
set {
this.resultsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified, Namespace="http://www.yahooapis.com/v1/base.rng")]
public string count {
get {
return this.countField;
}
set {
this.countField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified, Namespace="http://www.yahooapis.com/v1/base.rng")]
public string created {
get {
return this.createdField;
}
set {
this.createdField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified, Namespace="http://www.yahooapis.com/v1/base.rng")]
public string lang {
get {
return this.langField;
}
set {
this.langField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class queryResultsA {
private string hrefField;
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string href {
get {
return this.hrefField;
}
set {
this.hrefField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class NewDataSetA {
private queryA[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("query")]
public queryA[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
}
有什么想法吗?
根据我的评论,我将使用Linq将XML解析为XML,下面的代码可以工作,但我建议将解析分离到using语句之外,以便您可以处理Response和Streamreader。
public static YahooQueryResult LoadYahooResults(string url)
{
YahooQueryResult result = null;
WebRequest request = WebRequest.Create(path);
request.Timeout = 5000;
try
{
using (WebResponse response = request.GetResponse())
{
XDocument doc = XDocument.Load(response.GetResponseStream());
if (doc != null)
{
var query = doc.Root;
// Query Attribute Values
var count = int.Parse(query.Attributes().First(c => c.Name.LocalName == "count").Value);
var created = query.Attributes().First(c => c.Name.LocalName == "created").Value;
var lang = query.Attributes().First(c => c.Name.LocalName == "lang").Value;
var results = doc.Descendants().FirstOrDefault(r => (r.Name.LocalName == "results")).Descendants().Select(a => new Result() { ID = int.Parse(a.Attribute("href").Value.Replace("/dir/index?sid=", string.Empty).Trim()), Href = a.Attribute("href").Value, Text = a.Value }).ToList();
result = new YahooQueryResult() { Lang = lang, Created = created, Count = count, Results = results };
}
}
}
catch (Exception ex)
{
// Handle Exception
}
return result;
}
public class Result
{
public int ID { get; set; }
public string Href { get; set; }
public string Text { get; set; }
}
public class YahooQueryResult
{
public string Lang { get; set; }
public string Created { get; set; }
public int Count { get; set; }
public IEnumerable<Result> Results { get; set; }
}