不期望{“<user xmlns =”“>。}反序列化Twitter XML </user>

时间:2009-10-12 20:52:19

标签: c# twitter xml-serialization

我通过OAuth从Twitter中提取XML。

我正在向http://twitter.com/account/verify_credentials.xml发送请求,该请求返回以下XML:

<?xml version="1.0" encoding="UTF-8"?>
<user>
  <id>16434938</id>
  <name>Lloyd Sparkes</name>
  <screen_name>lloydsparkes</screen_name>
  <location>Hockley, Essex, UK</location>
  <description>Student</description>
  <profile_image_url>http://a3.twimg.com/profile_images/351849613/twitterProfilePhoto_normal.jpg</profile_image_url>
  <url>http://www.lloydsparkes.co.uk</url>
  <protected>false</protected>
  <followers_count>115</followers_count>
  <profile_background_color>9fdaf4</profile_background_color>
  <profile_text_color>000000</profile_text_color>
  <profile_link_color>220f7b</profile_link_color>
  <profile_sidebar_fill_color>FFF7CC</profile_sidebar_fill_color>
  <profile_sidebar_border_color>F2E195</profile_sidebar_border_color>
  <friends_count>87</friends_count>
  <created_at>Wed Sep 24 14:26:09 +0000 2008</created_at>
  <favourites_count>0</favourites_count>
  <utc_offset>0</utc_offset>
  <time_zone>London</time_zone>
  <profile_background_image_url>http://s.twimg.com/a/1255366924/images/themes/theme12/bg.gif</profile_background_image_url>
  <profile_background_tile>false</profile_background_tile>
  <statuses_count>1965</statuses_count>
  <notifications>false</notifications>
  <geo_enabled>false</geo_enabled>
  <verified>false</verified>
  <following>false</following>
  <status>
    <created_at>Mon Oct 12 19:23:47 +0000 2009</created_at>
    <id>4815268670</id>
    <text>&#187; @alexmuller your kidding? it should all be &quot;black tie&quot; dress code</text>
    <source>&lt;a href=&quot;http://code.google.com/p/wittytwitter/&quot; rel=&quot;nofollow&quot;&gt;Witty&lt;/a&gt;</source>
    <truncated>false</truncated>
    <in_reply_to_status_id>4815131457</in_reply_to_status_id>
    <in_reply_to_user_id>8645442</in_reply_to_user_id>
    <favorited>false</favorited>
    <in_reply_to_screen_name>alexmuller</in_reply_to_screen_name>
    <geo/>
  </status>
</user>

我正在使用以下代码进行反序列化:

    public User VerifyCredentials()
    {
        string url = "http://twitter.com/account/verify_credentials.xml";
        string xml = _oauth.oAuthWebRequestAsString(oAuthTwitter.Method.GET, url, null);

        XmlSerializer xs = new XmlSerializer(typeof(User),"");

        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml));

        return (User)xs.Deserialize(ms);
    }

我的User课程有以下内容:

 [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class User
{

    [XmlElement(ElementName = "id")]       
    public long Id { get; set; }

    [XmlElement(ElementName = "name")] 
    public string Name { get; set; }

    [XmlElement(ElementName = "screen_name")]       
    public string ScreenName { get; set; }

    [XmlElement(ElementName = "location")]       
    public string Location { get; set; }

    [XmlElement(ElementName = "description")]      
    public string Description { get; set; }

    [XmlElement(ElementName = "profile_image_url")]      
    public string ProfileImageUrl { get; set; }

    [XmlElement(ElementName = "url")]       
    public string Url { get; set; }

    [XmlElement(ElementName = "protected")]      
    public bool Protected { get; set; }

    [XmlElement(ElementName = "followers_count")]      
    public int FollowerCount { get; set; }

    [XmlElement(ElementName = "profile_background_color")]       
    public string ProfileBackgroundColor { get; set; }

    [XmlElement(ElementName = "profile_text_color")]       
    public string ProfileTextColor { get; set; }

    [XmlElement(ElementName = "profile_link_color")]       
    public string ProfileLinkColor { get; set; }

    [XmlElement(ElementName = "profile_sidebar_fill_color")]       
    public string ProfileSidebarFillColor { get; set; }

    [XmlElement(ElementName = "profile_sidebar_border_color")]      
    public string ProfileSidebarBorderColor { get; set; }

    [XmlElement(ElementName = "friends_count")]     
    public int FriendsCount { get; set; }

    [XmlElement(ElementName = "created_at")]     
    public string CreatedAt { get; set; }

    [XmlElement(ElementName = "favourties_count")]      
    public int FavouritesCount { get; set; }

    [XmlElement(ElementName = "utc_offset")]      
    public int UtcOffset { get; set; }

    [XmlElement(ElementName = "time_zone")]       
    public string Timezone { get; set; }

    [XmlElement(ElementName = "profile_background_image_url")]        
    public string ProfileBackgroundImageUrl { get; set; }

    [XmlElement(ElementName = "profile_background_tile")]        
    public bool ProfileBackgroundTile { get; set; }

    [XmlElement(ElementName = "statuese_count")]        
    public int StatusesCount { get; set; }

    [XmlElement(ElementName = "notifications")]       
    public string Notifications { get; set; }

    [XmlElement(ElementName = "geo_enabled")]       
    public bool GeoEnabled { get; set; }

    [XmlElement(ElementName = "Verified")]        
    public bool Verified { get; set; }

    [XmlElement(ElementName = "following")]
    public string Following { get; set; }

    [XmlElement(ElementName = "status", IsNullable=true)]
    public Status CurrentStatus { get; set; }

}

但是当它反序列化上面的XML时,应用程序抛出以下内容:

  • $ exception {“XML文档中存在错误(2,2)。”} System.Exception {System.InvalidOperationException}

  • InnerException {“&lt; user xmlns =''&gt;不是预期的。”} System.Exception {System.InvalidOperationException}

现在我已经搜索过了,我能找到的最佳解决方案是在序列化内容时向序列化程序添加空白名称空间,但我没有将其序列化,所以我不能。

我也有一些接收状态的代码,工作正常。

那么有人可以向我解释错误发生的原因吗?以及可能的解决方案?

提前致谢。

12 个答案:

答案 0 :(得分:218)

使用将在编译时使用的XmlRoot属性修饰您的根实体。

[XmlRoot(Namespace = "www.contoso.com", ElementName = "MyGroupName", DataType = "string", IsNullable=true)]

或者在运行时进行序列化时指定root属性。

XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "user";
// xRoot.Namespace = "http://www.cpandl.com";
xRoot.IsNullable = true;

XmlSerializer xs = new XmlSerializer(typeof(User),xRoot);

答案 1 :(得分:126)

更简单的方法就是将以下注释添加到班级的顶部:

[Serializable, XmlRoot("user")]
public partial class User
{
}

答案 2 :(得分:20)

XmlSerializer xs = new XmlSerializer(typeof(User), new XmlRootAttribute("yourRootName")); 

答案 3 :(得分:9)

错误信息是如此模糊,对我来说,我有这个代码:

var streamReader = new StreamReader(response.GetResponseStream());
var xmlSerializer = new XmlSerializer(typeof(aResponse));
theResponse = (bResponse) xmlSerializer.Deserialize(streamReader);

注意xmlSerializer是使用aResponse实例化的,但在反序列化时我将它意外地转换为bResonse。

答案 4 :(得分:4)

正如John Saunders所说,检查类/属性名称是否与XML的大写字母匹配。如果不是这种情况,也会出现问题。

答案 5 :(得分:4)

最简单和最好的解决方案是在您的类中使用 XMLRoot 属性,您希望在其中反序列化。

像:

[XmlRoot(ElementName = "YourPreferableNameHere")]
public class MyClass{
...
}

此外,请使用以下程序集

using System.Xml.Serialization;

答案 6 :(得分:2)

在我的案例中唯一有用的是使用大卫情人节代码。使用Root Attr。在Person类中没有帮助。

我有这个简单的Xml:

Logging made it here variables priv_blob_len_pointer 982750168 pub_blob_len_pointer 982750160 priv_blob_len -960449664 pub_blob_len -960449632 privkey 3a9395e0 pubkey f0b0b 
Logging param ID: 3 Oid 3a9395f8 : N: 0 Q: 38160144 P 19 Padded N: 0 D1: 11 D2: 0 D3: 0 
Logging Local N: 0 Q: 38160144 P 19 Padded N: 0 D1: 11 D2: 0 D3: 0 
Logging made it here variables priv_blob_len_pointer 982750168 pub_blob_len_pointer 982750160 priv_blob_len -960448960 pub_blob_len -960448920 privkey 3a9395e0 pubkey f0b0b 
Logging param ID: 3 Oid 3a9395f8 : N: 0 Q: 38160144 P 19 Padded N: 0 D1: 11 D2: 0 D3: 0 
Logging Local N: 0 Q: 38160144 P 19 Padded N: 0 D1: 11 D2: 0 D3: 0 

C#class:

<?xml version="1.0"?>
<personList>
 <Person>
  <FirstName>AAAA</FirstName>
  <LastName>BBB</LastName>
 </Person>
 <Person>
  <FirstName>CCC</FirstName>
  <LastName>DDD</LastName>
 </Person>
</personList>

从Main方法中反序列化C#代码:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

答案 7 :(得分:2)

对我来说没有任何帮助,这些错误

... was not expected, 
... there is an error in XML document (1,2)
... System.FormatException Input String was not in correct format ...

除了这种方式

1-您需要以字符串形式检查xml响应(您试图反序列化为对象的响应)

2-使用在线工具进行字符串unescape和xml prettify / formatter

3- 确保,您要尝试将xml字符串映射/反序列化为与该字符串的根元素匹配的 HAS AN XmlRootAttribute 的C#类(主类)响应。

例如:

我的XML响应就像:

<ShipmentCreationResponse xmlns="http://ws.aramex.net/ShippingAPI/v1/">
       <Transaction i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"/>
           ....

C#类定义+属性就像:

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.MessageContractAttribute(WrapperName="ShipmentCreationResponse", WrapperNamespace="http://ws.aramex.net/ShippingAPI/v1/", IsWrapped=true)]
public partial class ShipmentCreationResponse {
  .........
}

请注意,类定义没有“ XmlRootAttribute

[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://ws.aramex.net/ShippingAPI/v1/", IsNullable = false)]

当我尝试使用通用方法取消序列化时:

public static T Deserialize<T>(string input) where T : class
{
    System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));

    using (System.IO.StringReader sr = new System.IO.StringReader(input))
    {
        return (T)ser.Deserialize(sr);
    }
}





var _Response = GeneralHelper.XMLSerializer.Deserialize<ASRv2.ShipmentCreationResponse>(xml);

我遇到了以上错误

... was not expected, ... there is an error in XML document (1,2) ...

现在,只需添加永久修复该问题的“ XmlRootAttribute”,以及所有其他请求/响应,我都会遇到以下类似问题:

[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://ws.aramex.net/ShippingAPI/v1/", IsNullable = false)]

..

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ws.aramex.net/ShippingAPI/v1/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://ws.aramex.net/ShippingAPI/v1/", IsNullable = false)]
public partial class ShipmentCreationResponse
{
    ........
}

答案 8 :(得分:1)

我的问题是我的一个元素有xmlns属性:

<?xml version="1.0" encoding="utf-8"?>
<RETS ReplyCode="0">
    <RETS-RESPONSE xmlns="blahblah">
        ...
    </RETS-RESPONSE>
</RETS>

无论我尝试什么,xmlns属性似乎都破坏了序列化程序,所以我删除了xmlns =&#34; ...&#34;来自xml文件:

<?xml version="1.0" encoding="utf-8"?>
<RETS ReplyCode="0">
    <RETS-RESPONSE>
        ...
    </RETS-RESPONSE>
</RETS>
瞧,瞧!一切正常。

我现在解析xml文件以在反序列化之前删除此属性。 不知道为什么会这样,也许我的情况不同,因为包含xmlns属性的元素不是根元素。

答案 9 :(得分:1)

My issue was that the root element actually has a xmlns="abc123"

So had to make XmlRoot("elementname",NameSpace="abc123")

答案 10 :(得分:1)

以上所有内容均不适用于我,但这是: 检查类的Root元素的名称是否与XML 区分大小写中的名称完全相同。

答案 11 :(得分:0)

就我而言,我的xml具有多个名称空间和属性。 所以我用这个网站来生成对象-https://xmltocsharp.azurewebsites.net/

并使用下面的代码反序列化

 XmlDocument doc =  new XmlDocument();
        doc.Load("PathTo.xml");
        User obj;
        using (TextReader textReader = new StringReader(doc.OuterXml))
        {
            using (XmlTextReader reader = new XmlTextReader(textReader))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(User));
                obj = (User)serializer.Deserialize(reader);
            }
        }