{"<user xmlns =''>不是预期的.}反序列化Twitter XML

llo*_*kes 191 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>
Run Code Online (Sandbox Code Playgroud)

我使用以下代码来反序列化

    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);
    }
Run Code Online (Sandbox Code Playgroud)

我的用户类有以下内容

 [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; }

}
Run Code Online (Sandbox Code Playgroud)

但当它反序列化上面的Xml我得到以下错误抛出

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

  • InnerException {"<user xmlns =''>不是预期的."} System.Exception {System.InvalidOperationException}

现在我已经搜索过,我能找到的最佳解决方案是在序列化器中添加空白名称空间,当你序列化内容时,但我不能序列化它,所以我不能.

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

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

提前致谢

dav*_*ine 235

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

[XmlRoot(Namespace = "www.contoso.com", ElementName = "MyGroupName", DataType = "string", IsNullable=true)]
Run Code Online (Sandbox Code Playgroud)

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

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

XmlSerializer xs = new XmlSerializer(typeof(User),xRoot);
Run Code Online (Sandbox Code Playgroud)

  • XML区分大小写."用户"和"用户"是不同的名称. (37认同)
  • 您可以将类XmlRoot属性添加到类http://msdn.microsoft.com/en-us/library/83y7df3e(VS.71).aspx [XmlRoot(Namespace ="www.contoso.com",ElementName ="MyGroupName") ",DataType ="string",IsNullable = true)] (6认同)
  • 因为我认为XmlRoot信息应该在类本身上定义,而不是在反序列化的位置.对于这个原因,在我看来,Junto的解决方案是优越的. (4认同)
  • @GuiSim您假设OP可以控制原始实体.这两个答案都有效.在我的情况下,我不能将XmlRoot添加到实体,因为它被用作MessageContract的一部分.使用上述方法适用于我的场景. (4认同)
  • @GuiSim我不同意OP的说法.我完全控制了我的根实体但不能使用rootattribute,因为它与MessageContract属性冲突.这两个答案都是有效的,备选方案在评论中提出.关键是你投票给了一个有效的答案,而不是一个错误的答案.如果你不同意这是最好的只是不投票. (3认同)

Reb*_*cca 128

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

[Serializable, XmlRoot("user")]
public partial class User
{
}
Run Code Online (Sandbox Code Playgroud)


Ran*_*ddy 24

XmlSerializer xs = new XmlSerializer(typeof(User), new XmlRootAttribute("yourRootName")); 
Run Code Online (Sandbox Code Playgroud)

  • 对于无法依赖条件属性的情况,这非常棒. (2认同)
  • 很简单,完全修复了我的情况.谢谢! (2认同)

Jer*_*son 10

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

var streamReader = new StreamReader(response.GetResponseStream());
var xmlSerializer = new XmlSerializer(typeof(aResponse));
theResponse = (bResponse) xmlSerializer.Deserialize(streamReader);
Run Code Online (Sandbox Code Playgroud)

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

  • 刚遇到类似的问题.xmlserializer初始化为typeof(T),我正在转换为List <T> (2认同)

JoR*_*JoR 7

就我而言,我的 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);
            }
        }
Run Code Online (Sandbox Code Playgroud)

  • 该链接为将 xml 反序列化为类提供了巨大的帮助。 (3认同)

Kha*_*sim 6

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

喜欢:

[XmlRoot(ElementName = "YourPreferableNameHere")]
public class MyClass{
...
}
Run Code Online (Sandbox Code Playgroud)

此外,使用以下程序集

using System.Xml.Serialization;
Run Code Online (Sandbox Code Playgroud)

  • 有谁想解释一下吗?*为什么*需要`XmlRoot()`属性来解决这个问题?这里有 5 个答案说“只需添加此代码”,而不是一个解释。人们在 7 年后回答,它仍然只是“添加此 XmlRoot 代码”。在所有答案中,我选择了最新的一个来要求解释。 (5认同)

Luu*_*uuk 5

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