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 匹配的类/类
基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
