程序如下:
//json转xml
public static string JsonToXml(string json)
{
string xml = string.Empty;
XmlDocument xmlDoc = new XmlDocument();
try
{
XmlDictionaryReader xmlReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max);
xmlDoc.Load(xmlReader);
//json转xml
XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
//创建xml声明
xmlDoc.InsertBefore(xmlDec, xmlDoc.DocumentElement); //插入xml声明
//xmlDoc.AppendChild(xmlDec);
//添加xml声明
}
catch (Exception ex)
{
//
}
return xmlDoc.OuterXml; //xml转string
}
//xml 转 DataTable
public static DataTable GetDataTable(string xmlStr)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlStr);
//注意:这里的节点路径需要根据自己生成的xml 重新设置
XmlNodeList xlist = doc.SelectNodes("//root/item");
DataTable Dt = new DataTable();
DataRow Dr;
for (int i = 0; i < xlist.Count; i++)
{
Dr = Dt.NewRow();
XmlElement xe = (XmlElement)xlist.Item(i);
for (int j = 0; j < xe.Attributes.Count; j++)
{
if (!Dt.Columns.Contains("@" + xe.Attributes[j].Name))
Dt.Columns.Add("@" + xe.Attributes[j].Name);
Dr["@" + xe.Attributes[j].Name] = xe.Attributes[j].Value;
}
for (int j = 0; j < xe.ChildNodes.Count; j++)
{
if (!Dt.Columns.Contains(xe.ChildNodes.Item(j).Name))
Dt.Columns.Add(xe.ChildNodes.Item(j).Name);
Dr[xe.ChildNodes.Item(j).Name] = xe.ChildNodes.Item(j).InnerText;
}
Dt.Rows.Add(Dr);
}
return Dt;
}
json 示例:
{"insurancePlanName":"个人意外伤害保险","limitPerOccurrence":0,"payoutRatio":100,"specialAgreement":"这是一大段文字描述","sumInsured":10000},{"aggregateDeductible":0,"dailyBenefit":0,"deductibleDays":0,"deductiblePerOccurrence":0,"diseaseObservationDays":0,"dutyCode":"1143002","dutyName":"附加意外伤害医疗费用保险","dutyType":"其他类型","insurancePlanName":"个人意外伤害保险","limitPerOccurrence":0,"payoutRatio":100,"specialAgreement":"这是一大段文字描述","sumInsured":10000},{"aggregateDeductible":0,"dailyBenefit":0,"deductibleDays":0,"deductiblePerOccurrence":0,"diseaseObservationDays":60,"dutyCode":"1145005","dutyName":"附加住院费用补偿医疗保险","dutyType":"其他类型","insurancePlanName":"个人意外伤害保险","limitPerOccurrence":0,"payoutRatio":100,"specialAgreement":"这是一大段文字描述","sumInsured":100000},{"aggregateDeductible":0,"dailyBenefit":0,"deductibleDays":0,"deductiblePerOccurrence":0,"diseaseObservationDays":60,"dutyCode":"1145005","dutyName":"附加住院费用补偿医疗保险","dutyType":"其他类型","insurancePlanName":"个人意外伤害保险","limitPerOccurrence":0,"payoutRatio":100,"specialAgreement":"这是一大段文字描述","sumInsured":100000},{"aggregateDeductible":0,"dailyBenefit":0,"deductibleDays":0,"deductiblePerOccurrence":0,"diseaseObservationDays":0,"dutyCode":"1145004","dutyName":"附加住院定额给付医疗保险","dutyType":"补贴类型","insurancePlanName":"个人意外伤害保险","limitPerOccurrence":0,"payoutRatio":0,"specialAgreement":"1这是一大段文字描述","sumInsured":18000}],}
转换成xml 的示例: