我有一些带有这样元素的 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 **