将Xml与许多级别转换为一个DataTable [英] Convert Xml with a lot of levels to one DataTable
问题描述
如何在一个DataTable中将XML与许多级别和参数进行融合?
我需要一些像Excel的xml导入一样的东西:
How I can conver XML with a lot of levels and parameters in one DataTable? I need somthing like do Excel with xml import:
<?xml version='1.0' encoding='UTF-8'?>
<Document>
<tag1 param1="param">
<tag2 param2="param">
<tag3 param3="param">
<tag4_1 param41="param">VALUE1</tag4_1>
<tag4_2 param42="param">VALUE2</tag4_2>
</tag3>
</tag2>
</tag1>
<tag1 param1="param">
<tag2 param2="param">
<tag3 param3="param">
<tag4_1 param41="param">VALUE1</tag4_1>
<tag4_2 param42="param">VALUE2</tag4_2>
</tag3>
</tag2>
</tag1>
</Document>
Excel示例:
它有一个简单的方法吗?
Is it have a simple method to do it?
解决方案 - 这不是我想要的,因为这里会有很多表:
This solution - it's NOT that I want, because here will be a lot of tables:
var dataSet = new DataSet();
dataSet.ReadXml(xml, XmlReadMode.InferSchema);
推荐答案
如果你知道xml的架构,你可以做一个数据类,它将与模式匹配,只需使用XmlSerializer,然后将Data对象传递到数据表中。
If you know the schema of the xml, you could do a data class, which would match the schema and simply use XmlSerializer, then pass the Data object into the data table.
使用普通的XMLDocument函数加载xml和将其转换成字符串
Use a normal XMLDocument function to load the xml and convert it into string
将xml转换为字符串
var t = new System.Xml.XmlDocument();
t.Load("PATH");
t.OuterXml
将XML转换为数据对象
Converting the XML to a Data object
public static object ObjectFromXMLString(Type typeOfObject, string xmlFile)
{
XmlSerializer serializer = new XmlSerializer(typeOfObject);
StringReader rdr = new StringReader(xmlFile);
return serializer.Deserialize(rdr);
}
这篇关于将Xml与许多级别转换为一个DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!