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

How to read XML into a class/classes that matches its xsd(如何将 XML 读入与其 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 匹配的类/类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)