問題描述
所以我有一個(gè) XSD 和一個(gè)以相同格式提供的 Web 服務(wù).
現(xiàn)在我可以繼續(xù)將 xml 讀入文檔,從類中創(chuàng)建我的對(duì)象等......但我在想,必須有一些更簡單的方法來做到這一點(diǎn).
我說的對(duì)嗎?;)
- 解決方案
您可以使用 XmlSerializer 將 XML 文本反序列化為由 xsd.exe 生成的類的實(shí)例.
XmlSerializer 將使用 元數(shù)據(jù)屬性 放置在生成的類上以在 XML 元素和對(duì)象之間來回映射.string xmlSource = "<ResultSet><Resultprecision="address"><Latitude>47.643727</Latitude></Result></ResultSet>";XmlSerializer 序列化器 = new XmlSerializer(typeof(ResultSet));結(jié)果集輸出;使用 (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); }
這篇關(guān)于如何將 XML 讀入與其 xsd 匹配的類/類的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!