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

2

本文介绍了如何将 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 匹配的类/类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

    The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14