当标记的名称与类的名称不同时,无法反序列化xml [英] Unable to deserialize xml when the name of the tag is different from the name of the class

查看:77
本文介绍了当标记的名称与类的名称不同时,无法反序列化xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我在Visual Studio 2008中使用C#来利用已暴露给我的应用程序的某些Web服务。

我从webservice调用获得响应后,我需要反序列化innerXml内容一个XmlElement并将其转换为我可能在其后使用的对象。但是,当xml元素的标记名称与对象的相应类名称不同时,似乎反序列化失败。

例如,以下xml成功反序列化为类"shoes"的对象< br< shoes>
< shoes> 2< / shoes>
<访问>否< / access>
< misc>否< misc>
< / footwear> < br>
公共级鞋类

公共级鞋类;
public string access;
public string misc;
}

但是,当我的类名称为'footwear222'时,反序列化失败并显示错误"xmlns不是预期"


公共类鞋类222 {$


公共字符串鞋;

公共字符串访问;

公共字符串misc;

}

我无法更改xml标签的名称或者因为我'从其他地方接收此信息。是否可以使用具有不同名称但与xml具有相同结构的类来将其成功反序列化为对象?

非常感谢!


解决方案

您可以设置控制XML序列化的某些属性

< tr>
[XmlElement( ElementName = " footwear" )]
public class footwear222
{
...
}


I'm using C# with Visual Studio 2008 to utilize certain webservices that have been exposed to my application.

After I obtain the response from the webservice call, I need to deserialize the innerXml content of an XmlElement and convert it into an object which I may use thereafter. However, it seems that deserialzing fails when the name of the xml element's tag is different from the corresponding class name of the object.

For example the following xml is successfully deserialized into an object of the class 'footwear'
 <footwear>
    <shoes>2</shoes>
    <access>No</access>
    <misc>No<misc>
 </footwear>

public class footwear{
 
           public string shoes;
           public string access;
           public string misc;
}

However, when the name of my class is 'footwear222'  for example, deserialization fails with an error that "xmlns was not expected"

public class footwear222{
 
           public string shoes;
           public string access;
           public string misc;
}

I cannot change the name of the xml tags or the since I'm receiving this information from elsewhere.
Is it possible to use a class with a different name but the same structure as the xml to deserialize it successfully into an object??

Thanks a ton!


解决方案

Well there are certain attributes you can set to control XML serialization:

[XmlElement(ElementName="footwear")] 
public class footwear222 
  ... 


这篇关于当标记的名称与类的名称不同时,无法反序列化xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆