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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1556874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:49:06  来源:igfitidea点击:

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

c#twitterxml-serialization

提问by lloydsparkes

I'm pulling in the XML from Twitter via OAuth.

我正在通过 OAuth 从 Twitter 中提取 XML。

I'm doing a request to http://twitter.com/account/verify_credentials.xml, which returns the following 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>

I am using the following code to Deserialize:

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

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

And I have the following for my Userclass:

我的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; }

}

But when it's deserializing the above XML the application throws the following:

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

  • $exception {"There is an error in XML document (2, 2)."} System.Exception {System.InvalidOperationException}

  • InnerException {"<user xmlns=''> was not expected."} System.Exception {System.InvalidOperationException}

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

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

Now I have searched around and the best solution I can find is to add blank namespaces to the serializer when you serialize the content, but i'm not serializing it so I can't.

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

I also have some code for receiving Statuses, which works fine.

我还有一些用于接收状态的代码,效果很好。

So can someone explain to me why the error is happening? As well as a possible solution?

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

Thanks in advance.

提前致谢。

采纳答案by david valentine

Either decorate your root entity with the XmlRoot attribute which will be used at compile time.

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

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

Or specify the root attribute when de serializing at runtime.

或者在运行时反序列化时指定根属性。

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

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

回答by Luuk

As John Saunders says, check if the class/property names matches the capital casing of your XML. If this isn't the case, the problem will also occur.

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

回答by Rebecca

Even easier is just to add the following annotations to the top of your class:

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

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

回答by Jeremy Thompson

The error message is so vague, for me I had this code:

错误信息太模糊了,对我来说我有这个代码:

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

Notice xmlSerializer is instantiated with aResponse but on deserializing I accidentally casted it to bResonse.

注意 xmlSerializer 是用 aResponse 实例化的,但是在反序列化时我不小心将它强制转换为 bResonse。

回答by Ranadheer Reddy

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

回答by Patrick Borkowicz

My problem was one of my elements had the xmlns attribute:

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

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

No matter what I tried the xmlns attribute seemed to be breaking the serializer, so I removed any trace of xmlns="..." from the xml file:

无论我尝试什么 xmlns 属性似乎都破坏了序列化程序,所以我从 xml 文件中删除了 xmlns="..." 的任何痕迹:

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

and voila! Everything worked.

瞧!一切正常。

I now parse the xml file to remove this attribute before deserializing. Not sure why this works, maybe my case is different since the element containing the xmlns attribute is not the root element.

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

回答by user2596085

The only thing that worked in my case was by using david valentine code. Using Root Attr. in the Person class did not help.

在我的案例中唯一有效的方法是使用 david valentine 代码。使用根属性。在 Person 类中没有帮助。

I have this simple Xml:

我有这个简单的 Xml:

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

C# class:

C# 类:

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

De-Serialization C# code from a Main method:

来自 Main 方法的反序列化 C# 代码:

XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "personList";
xRoot.IsNullable = true;
using (StreamReader reader = new StreamReader(xmlFilePath))
{
List<Person> result = (List<Person>)(new XmlSerializer(typeof(List<Person>), xRoot)).Deserialize(reader);
 int numOfPersons = result.Count;
}  

回答by Khawaja Asim

The simplest and best solution is just to use XMLRootattribute in your class, in which you wish to deserialize.

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

Like:

喜欢:

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

Also, use the following Assembly:

此外,使用以下程序集

using System.Xml.Serialization;

回答by Nick

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

我的问题是根元素实际上有一个 xmlns="abc123"

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

所以不得不让 XmlRoot("elementname",NameSpace="abc123")

回答by shdr

All above not worked for me, but this was: Check that the name of Root element of class is exactlylike the one from XML case sensitive.

上述所有不为我工作,但这是:检查类的根元素的名称是完全相同像XML的一个区分大小写