問題描述
所以我有一個 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 匹配的類/類的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!