如何将XML读入与其xsd匹配的类/类

Kje*_*sen 13 .net c# xml xsd xsd.exe

所以我有一个XSD和一个以相同格式提供的web服务.

现在我可以继续将xml读入文档,从类中创建我的对象等......但我在想,必须有一些更简单的方法来做到这一点.

我对吗?;)

<ResultSet xsi:schemaLocation="urn:yahoo:maps http://api.local.yahoo.com/MapsService/V1/GeocodeResponse.xsd">
 <Result precision="address">
  <Latitude>47.643727</Latitude>
  <Longitude>-122.130474</Longitude>
  <Address>1 Microsoft Way, #Way1</Address>
  <City>Redmond</City>
  <State>WA</State>
  <Zip>98052-6399</Zip>
  <Country>US</Country>
 </Result>
</ResultSet>
Run Code Online (Sandbox Code Playgroud)

下面是使用xsd.exe自动生成的类(实际上是两个)

类图http://i43.tinypic.com/2rf7j41.png

Enr*_*lio 22

您可以使用XmlSerializer将XML文本反序列化为xsd.exe生成的类的实例.
XmlSerializer将使用放置在生成的类上的元数据属性在XML元素和对象之间来回映射.

string xmlSource = "<ResultSet><Result precision=\"address\"><Latitude>47.643727</Latitude></Result></ResultSet>";

XmlSerializer serializer = new XmlSerializer(typeof(ResultSet));
ResultSet output;

using (StringReader reader = new StringReader(xmlSource))
{
    output = (ResultSet)serializer.Deserialize(reader);
}
Run Code Online (Sandbox Code Playgroud)