【发布时间】:2018-09-17 18:39:56
【问题描述】:
我正在尝试将给定的 XML 文件反序列化为对象结构。
这是 XML:
<StaticData>
<Configuration>
<SqlCmdParameters />
<Tables>
<Table Schema="dbo" Name="table1">
<Columns>
<Column Name="tab1col1" IsPrimaryKey="false" />
<Column Name="tab1col2" IsPrimaryKey="false" />
</Columns>
</Table>
<Table Schema="dbo" Name="table2">
<Columns>
<Column Name="tab2col1" IsPrimaryKey="false" />
<Column Name="tab2col2" IsPrimaryKey="false" />
</Columns>
</Table>
</Tables>
</Configuration>
<TableDataItems>
<TableData Schema="dbo" Name="table1">
<RowData tab1col1="11" tab1col2="text1" tab1col3="anotherText1" />
<RowData tab1col1="12" tab1col2="text2" tab1col3="anotherText2"/>
<RowData tab1col1="13" tab1col2="text3" tab1col3="anotherText3"/>
</TableData>
<TableData Schema="dbo" Name="table2">
<RowData tab2col1="22" tab2col2="text1" />
<RowData tab2col1="23" tab2col2="text1" />
<RowData tab2col1="24" tab2col2="text1" />
</TableData>
</TableDataItems>
</StaticData>
我要填写的类是:
[XmlRoot("StaticData")]
public class StaticData
{
[XmlElement("Configuration")]
public Configuration Configuration { get; set; }
[XmlElement("TableDataItems")]
public TableDataItems TableDataItems { get; set; }
}
public class Configuration
{
[XmlElement("Tables")]
public List<Table> Tables { get; set; }
[XmlElement("SqlCmdParameters")]
public List<SqlCommandParameter> SqlCommandParameters { get; set; }
}
public class TableDataItems
{
[XmlElement("TableData")]
public List<Table> TableDatas { get; set; }
}
public class Table
{
[XmlAttribute("Name")]
public string TableName { get; set; }
[XmlAttribute("Schema")]
public string SchemaName { get; set; }
[XmlElement("Columns")]
public List<Column> Columns { get; set; }
[XmlElement("RowData")]
public List<Row> Rows { get; set; }
public Table()
{
Columns = new List<Column>();
Rows = new List<Row>();
}
}
public class Column
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlAttribute("IsPrimaryKey")]
public bool IsPrimaryKey { get; set; }
}
public class Row
{
public Row()
{
RowData = new Dictionary<string, string>();
}
???What Attribute should I put here???
public Dictionary<string, string> RowData { get; set; }
}
所以,一切正常,直到我到达应该将所有属性填充到字典中的位置。
到目前为止,这就是我反序列化 XML 的方式:
public void CreateObjectStructureFromXml()
{
using (TextReader textReader = new StringReader(XmlDocument.ToString()))
{
XmlSerializer serializer = new XmlSerializer(typeof(StaticData));
StaticData = (StaticData) serializer.Deserialize(textReader);
}
}
我一到达 Row 元素就得到一个异常。
谁能指出我犯错的地方或我应该怎么做? XML RowData 可以带有可变数量的属性。属性是数据库表的内容。
提前非常感谢
【问题讨论】:
-
我会像
<TableData Schema="dbo" Name="table2"><RowData><ColData Name="tab2col1">22</ColData><ColData Name="tab2col2">someValue</ColData> </RowData></TableData>那样重新构建我的 XML 以使其更具可扩展性,这也将有助于在您的代码中创建等效的映射结构 -
如果您不控制 XML 文件的创建,那么您将不得不通过自定义序列化来实现您的需求 - stackoverflow.com/questions/17236823/… AND docs.microsoft.com/en-us/dotnet/standard/serialization/…
标签: c# xml dictionary deserialization