How to read XML into a class/classes that matches its xsd(如何将 XML 读入与其 xsd 匹配的类/类)
问题描述
所以我有一个 XSD 和一个以相同格式提供的 Web 服务.
现在我可以继续将 xml 读入文档,从类中创建我的对象等......但我在想,必须有一些更简单的方法来做到这一点.
我说的对吗?;)
- 解决方案
您可以使用 XmlSerializer 将 XML 文本反序列化为由 xsd.exe 生成的类的实例.
XmlSerializer 将使用 元数据属性 放置在生成的类上以在 XML 元素和对象之间来回映射.string xmlSource = "<ResultSet><Resultprecision="address"><Latitude>47.643727</Latitude></Result></ResultSet>";XmlSerializer 序列化器 = new XmlSerializer(typeof(ResultSet));结果集输出;使用 (StringReader reader = new StringReader(xmlSource)){输出 = (ResultSet)serializer.Deserialize(reader);}
So I have an XSD and a webservice that delivers in that same format.
Now I could go ahead and read the xml into a document, create my objects from the class etc... But I am thinking, there must be some easier way to do that.
Am I right? ;)
- Yahoo Maps GeocodeResponse XSD
- Yahoo Maps GeocodeResponse sample
<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>
Below are auto-generated classes (two actually), using xsd.exe
解决方案You could use the XmlSerializer to deserialize the XML text into instances of the classes generated by xsd.exe.
The XmlSerializer will use the metadata attributes placed on the generated classes to map back and forth between XML elements and objects.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); }
这篇关于如何将 XML 读入与其 xsd 匹配的类/类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 XML 读入与其 xsd 匹配的类/类
基础教程推荐
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01