【发布时间】:2012-05-09 03:24:29
【问题描述】:
我有一些带有如下元素的 XML:
<hour base_forecast="12" datim="29/0" />
我收到错误:
Unexpected node type Element. ReadElementString method can only be
called on elements with simple or empty content.
我猜这是因为元素没有价值。我不控制这个 XML,所以我不能改变它。我将如何反序列化它?
** 编辑 **
其中一个属性的值是 ">6" .... 这可能是罪魁祸首吗?如果是这样,我该如何处理?
** 更新**
在属性值中发现了一些未返回 > 的数据。发生同样的错误。
** 编辑 #3 * 为我收到的 XML 创建了一个 XSD,然后使用 xsd 工具为它们生成了类。添加到这篇文章的底部。
这里是反序列化代码:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("xxx");
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
WeatherData Result = new WeatherData();
using (Stream st = resp.GetResponseStream())
{
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "model_data";
xRoot.IsNullable = true;
Result = new XmlSerializer(typeof(WeatherData), xRoot).Deserialize(st) as WeatherData; ** Error here
Xml 返回:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE observation SYSTEM "http://private.com/hithere.dtd">
<model_data>
<site a="28/12" b="KXXX">
<hour x="-9999" y="-9999" z="-9999"/>
</site>
</model_data>
数据对象
[Serializable, XmlRoot("model_data")]
public class WeatherData
{
[XmlElement("site")]
public string City { get; set; }
[XmlAttribute]
public string a { get; set; }
[XmlAttribute]
public string b { get; set; }
[XmlElement(ElementName="hour", IsNullable=true)]
public string Hour { get; set; }
[XmlAttribute]
public string x { get; set; }
[XmlAttribute]
public string y { get; set; }
[XmlAttribute]
public string z { get; set; }
}
XSD 工具生成的类
**Removed generated classes, but they are similar to what Hugo posted **
【问题讨论】:
-
您是否可能从
<hour>的父级调用ReadElementString,或者您的读者不在您认为的位置? -
将编辑帖子并提供一些代码。
-
如果我将流转储到 XmlDocument 中然后尝试反序列化,我看到反序列化器在抛出错误时处于元素小时。在这种格式中,错误也会出现在
开始的正确行和位置。 -
你究竟想进入
[XmlElement("site")]public string City { get; set; }
标签: c# xml-serialization