所以我有一个 XSD 和一个以相同格式提供的网络服务。
现在我可以继续将 xml 读入文档,从类中创建我的对象等...但我在想,必须有一些更简单的方法来做到这一点。
我说的对吗? ;)
<pre><code><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>
</code></pre>
下面是自动生成的类(实际上是两个),使用xsd.exe
最佳答案
您可以使用 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);
}
关于c# - 如何将 XML 读入与其 xsd 匹配的类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/792976/