0

我正在使用此代码从 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.

我该如何解决?

4

2 回答 2

0

Just adding a very specific solution for this problem, have a look at @MarcGravell's answer for the generic solution.

> 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

And the final C# code:

xedatafeed reply = null;

using (var wc = new WebClient()) // Catching exceptions is for pussies! :)
  reply = ParseXml<xedatafeed>(wc.DownloadString(uri));

With the following method defined:

T ParseXml<T>(string data) {
  return (T) new XmlSerializer(typeof(T)).Deserialize(new StringReader(data));
}

My guess is that you had some issues with LinqToXSD and its generation.

于 2013-09-12T13:24:55.237 回答
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合适的类以匹配)

于 2013-09-12T10:50:07.990 回答