我正在尝试解析以下原子XML提要:
<dealer version="1.12" xmlns:atom="http://www.w3.org/2005/Atom"><atom:link rel="self" href="http://Blah.com/dealers/1234"/><atom:link rel="http://Blah.com/rels/dealer_notification_prefs" href="http://Blah.com/dealers/1234/notification_prefs"/><atom:link rel="http://Blah.com/rels/dealer_systems" href="http://Blah.com/dealers/1234/systems"/><atom:link rel="http://Blah.com/rels/dealer_logo" href="http://Blah.com/dealers/1234/logo"/><pid>1234</pid><name>ABC Heating & Air Conditioning</name><first>X</first><last>X</last><street1>PO Box 321</street1><street2/><city>Orson</city><state>IN</state><country>United States</country><postal>46142</postal><phone>317-555-5555</phone><phoneExt/><url></url><email>someone@noemail.com</email></dealer>
我使用的C#代码是:
using (var client = new HttpClient()) // Using block for disposing of HttpClient when finished
{
client.DefaultRequestHeaders.Accept.Clear();
client.BaseAddress = new Uri(_baseUriPart); // Set to core base Uri for whole Api
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", _builtParamsString);
// Send HTTP Requests Async
try
{
bool respSuccess = false;
HttpResponseMessage response = await client.GetAsync(_resourceUriPart);
//HttpResponseMessage response = await client.SendAsync(myRequestTest);
response.EnsureSuccessStatusCode(); // Throw Exception if not a success code. // ...}
Stream stream = await response.Content.ReadAsStreamAsync();
var prereader = new StreamReader(stream);
string readContent = prereader.ReadToEnd();
string readOut = string.Empty;
TextReader tr = new StringReader(readContent);
XmlReader reader = XmlReader.Create(tr);
SyndicationFeed feed = SyndicationFeed.Load(reader);
if(null!=feed)
{
foreach(var item in feed.Items)
{
//readOut = readOut + item.Title.Text + ":" + ((TextSyndicationContent)item.Content).Text+ Environment.NewLine;
}
}
respSuccess = response.IsSuccessStatusCode;
TextBox1.Text = respSuccess.ToString();
TextBox2.Text = response.StatusCode.ToString();
TextBox3.Text = readOut;
}
catch (HttpRequestException e)
{
TextBox1.Text = "False";
TextBox2.Text = "See Content Message";
TextBox3.Text = e.Message;
}
} // End using block
我可以连接到网络服务,并请求经销商信息。但是当SyndicationFeed开始读取XML时我得到的错误是:
“名称为'dealer'且名称空间''的元素不是允许的Feed格式。”
有人可以帮我解释一下吗?感谢!!!
答案 0 :(得分:0)
dealer
不是原子Feed根的有效标记。有关详细信息,请参阅Atom Syndication Format RFC。它应该是atom:feed
。
很遗憾,找到无效的RSS / Atom供稿非常常见。 SyndicationFeed
是严格的,因此您必须对输入数据进行一些按摩以使其正常工作。
这很难看,但简单的方法是为String.Replace
代码执行dealer
。
// ...
readContent = readContent.Replace("<dealer ", "<atom:feed ").Replace("</dealer>", "</atom:feed>");
TextReader tr = new StringReader(readContent);
// ...
我过去也通过从XmlTextReader派生并修复坏元素来修复Feed。