我正在使用此代码从XE.COM读取XML数据
string url = ConfigurationManager.AppSettings[CONFIGURATION_KEY_XE_COM_URL];
System.Xml.Serialization.XmlSerializer ser =
new System.Xml.Serialization.XmlSerializer(typeof(xedatafeed));
// try XmlReader
XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = null;
settings.DtdProcessing = DtdProcessing.Parse;
System.Xml.XmlReader reader = System.Xml.XmlReader.Create(url, settings);
string reply = (string)ser.Deserialize(reader);
// try WebClient
System.Net.WebClient client = new System.Net.WebClient();
string data = Encoding.UTF8.GetString(client.DownloadData(url));
问题是这一行
xedatafeed reply = (string)ser.Deserialize(xedatafeed);
正在抛出异常
<xe-datafeed xmlns=''> was not expected.
我该如何解决这个问题?
答案 0 :(得分:0)
似乎数据返回了一些形式的xml:
<xe-datafeed>...</xe-datafeed>
您需要做的是:编写一个映射到该xml 的类型,并对其进行注释 - 例如:
[XmlRoot("xe-datafeed")]
public class XeDataFeed {
// properties here, annotated with [XmlElement(...)], [XmlAttribute(...)], etc
}
然后在您的代码中使用它:
var ser = new XmlSerializer(typeof(XeDataFeed));
//...
var obj = (XeDataFeed)ser.Deserialize(reader);
如果模型很大,您也可以使用xsd.exe
工具来提供帮助:
xsd some.xml
(检查some.xml
并生成some.xsd
)
xsd somd.xsd /classes
(检查some.xsd
并使用合适的类生成some.cs
)
答案 1 :(得分:0)
只需为此问题添加一个非常具体的解决方案,请查看@ MarcGravell对通用解决方案的回答。
> wget http://www.xe.com/datafeed/samples/sample-xml-usd.xml
> xsd sample-xml-usd.xml
// generating xsd, change xs:string to xs:decimal for crate and cinverse though
> xsd sample-xml-usd.xsd /classes
// now we have created sample-xml-usd.cs, c# classes representing the xml
最后的C#代码:
xedatafeed reply = null;
using (var wc = new WebClient()) // Catching exceptions is for pussies! :)
reply = ParseXml<xedatafeed>(wc.DownloadString(uri));
定义了以下方法:
T ParseXml<T>(string data) {
return (T) new XmlSerializer(typeof(T)).Deserialize(new StringReader(data));
}
我的猜测是你在LinqToXSD
及其生成方面遇到了一些问题。