问题描述
传入参数:stringstrXml="<StockInDetails><StockInDetail><id>2615905</id><pid>502649</pid><ownerId>4332</ownerId><ownerCode>3122446934</ownerCode><ownerName></ownerName><billNo>2358I201501057912088</billNo><cid>8150682</cid><qty>213.000000</qty><money>195.960000</money><gWeight>2.272300</gWeight><nWeight>2.130000</nWeight><cQty>0.000000</cQty><sQty>17.000000</sQty><tag>SH1229F02-2</tag><mergerCargoId>M1420429480772</mergerCargoId><orgCargoId>Y1420429480807</orgCargoId><hsCode>8536901100</hsCode><gName></gName><model>418234</model><unit>007</unit><curr>303</curr><country>304</country><cargoType>13</cargoType><cWeight>0.000000</cWeight><sWeight>0.170000</sWeight><cMoney>0.000000</cMoney><sMoney>15.640000</sMoney><usdMoney>334.343621</usdMoney><cusNo>221820141185146968</cusNo></StockInDetail></StockInDetails>";反序列化方法:publicstaticDataTableFromXmlDataTable(stringstrXml){StringReaderstrReader=newStringReader(strXml);XmlReaderxmlReader=XmlReader.Create(strReader);try{DataTabledt=default(DataTable);XmlSerializerserializer=newXmlSerializer(typeof(DataTable));if(serializer.CanDeserialize(xmlReader)){dt=serializer.Deserialize(xmlReader)asDataTable;}xmlReader.Close();strReader.Close();returndt;}catch(Exceptionex){throwex;}finally{if(xmlReader!=null){xmlReader.Close();}if(strReader!=null){strReader.Close();}}}错误:{"XML文档(1,2)中有错误。"}用户代码未处理System.ExceptionHResult=-2146233088Message=不应有<StockInDetailsxmlns=''>。Source=WebStackTrace:在Web.WebService.DataUploadWebService.UploadStockInListService(StringstrStockInList,StringuserId,List`1param)位置e:Work3.SourceWebWebServiceDataUploadWebService.asmx.cs:行号92InnerException:HResult=-2146233088Message=在Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderDataTable.Read1_DataTable()InnerException:
解决方案
解决方案二:
看样子是因为NameSpace为空导致的,可以使用newXmlSerializer(Type,XmlNameSpace)的重载dataTable本身就封装有现成的WriteXml和ReadXml方法
解决方案三:
解决方案四:
您好,我是讲XML文件反序列化成datatable
解决方案五:
哥,你就不能犯序列化成List<T>的?为什么一定要DataTable呢?
解决方案六:
//用表名指定行节点名vardt=newDataTable("StockInDetail");dt.Columns.AddRange(newDataColumn[]{newDataColumn("id",typeof(int)),newDataColumn("pid",typeof(int)),//...});varsr=newStringReader(strXml);using(varxr=XmlTextReader.Create(sr)){dt.ReadXml(xr);}
解决方案七:
不过xml一般首先实体对象序列化,比table方便
解决方案八:
引用5楼dongxinxi的回复:
//用表名指定行节点名vardt=newDataTable("StockInDetail");dt.Columns.AddRange(newDataColumn[]{newDataColumn("id",typeof(int)),newDataColumn("pid",typeof(int)),//...});varsr=newStringReader(strXml);using(varxr=XmlTextReader.Create(sr)){dt.ReadXml(xr);}
正解,你的XML从何而来?如果是通过DataTable序列化而来,注意把元数据带出来;如果是自己拼出来的,反序列化时就要手动初始化元数据了。
解决方案九:
你这个XML不是由Table序列化得来的,谈何返序列化。。。