C# 如何将 XML 读入与其 xsd 匹配的类/类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/792976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read XML into a class/classes that matches its xsd
提问by Kjensen
So I have an XSD and a webservice that delivers in that same format.
所以我有一个 XSD 和一个以相同格式提供的 web 服务。
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.
现在我可以继续将 xml 读入文档,从类中创建我的对象等等......但我在想,必须有一些更简单的方来做到这一点。
Am I right? ;)
我对吗?;)
<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>
<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
下面是自动生成的类(实际上是两个),使用xsd.exe
采纳答案by Enrico Campidoglio
You could use the XmlSerializerto deserialize the XML text into instances of the classes generated by xsd.exe.
The XmlSerializer will use the metadata attributesplaced on the generated classes to map back and forth between XML elements and objects.
您可以使用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);
}
回答by BobbyShaftoe
You could just create a Typed DataSet from the XSD and then fill one of those objects with the XML. That's the pretty common method.
您可以从 XSD 创建一个 Typed DataSet,然后用 XML 填充其中一个对象。这是很常见的方。
回答by Colin
The XSD Code Generatorin Liquid XML Studio does a great job of creating highly compliant c# or vb.net code from an XML Schema. This code can then be used to call or implement a web service.
Liquid XML Studio 中的XSD 代码生成器在从 XML 模式创建高度兼容的 c# 或 vb.net 代码方面做得很好。然后可以使用此代码来调用或实现 Web 服务。
If your implementing a web service then you can take control of the WSDL produced using XmlSchemaProvider and IXmlSerializable, see Taking Control of your WSDL
如果您实现了 Web 服务,那么您可以控制使用 XmlSchemaProvider 和 IXmlSerializable 生成的 WSDL,请参阅控制您的 WSDL