如何从 XML 字符串反序列化对象?
我尝试使用 xmlSerializer.Deserialize() 将对象从 XML 字符串反序列化,但返回的对象始终为空(不为 null,但所有属性均为 null 或 0)。我无法弄清楚我做错了什么,但我没有收到任何错误或异常。
string xml = "***my xml is here***";
XmlSerializer ser = new XmlSerializer(typeof(Order));
StringReader stringReader = new StringReader(xml);
XmlTextReader xmlReader = new XmlTextReader(stringReader);
Order order = (Order)ser.Deserialize(xmlReader);
xmlReader.Close();
stringReader.Close();
Order.cs 的源代码是使用 xsd.exe 工具从 XSD 生成的。
order.cs 来源: http://www.nickgilbert.com/etc/1/Order .txt
示例订单 XML:http://www.nickgilbert.com /etc/1/example-order.xml
I'm trying to deserialize an object back from it's XML string using xmlSerializer.Deserialize() but the returned object is always blank (not null, but all the properties are null or 0). I can't work out what I'm doing wrong and yet I get no errors or exceptions.
string xml = "***my xml is here***";
XmlSerializer ser = new XmlSerializer(typeof(Order));
StringReader stringReader = new StringReader(xml);
XmlTextReader xmlReader = new XmlTextReader(stringReader);
Order order = (Order)ser.Deserialize(xmlReader);
xmlReader.Close();
stringReader.Close();
The source of Order.cs was generated from the XSD using the the xsd.exe tool.
Source of order.cs: http://www.nickgilbert.com/etc/1/Order.txt
Sample order XML: http://www.nickgilbert.com/etc/1/example-order.xml
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的示例 XML 文件 (example-order.xml) 使用命名空间
http://tempuri.org/OrderSchema.xsd
,但 XSD (order.cs) 生成的代码定义了命名空间http://x-rm.com/wrightcottrell/cataloguecd/
。您需要匹配这些命名空间才能使序列化正常工作。
Your sample XML file (example-order.xml) uses the namespace
http://tempuri.org/OrderSchema.xsd
but the code generated by XSD (order.cs) defines all of the elements in the namespacehttp://x-rm.com/wrightcottrell/cataloguecd/
.You'll need these namespaces to match up in order for serialization to work properly.
事实上,您完全返回了一个对象,这告诉我该对象是公共的,并且有一个公共的无参数构造函数(否则会抛出异常)。因此,它很可能会失败之一:
get
和公共set
的公共属性,或者默认情况下 成员名称必须与 xml 元素 名称完全匹配,且与父元素位于同一 xml 命名空间中;可以通过属性获得更精细的控制(更改名称、使用属性、命名空间等)The fact that you get an object back at all tells me that the object is public and has a public parameterless constructor (otherwise an exception would have been thrown). So, it is most-likely failing one of:
get
and publicset
, or public (non-readonly) fields