我创建了一个XML模型,用于将SQL结果集转换为XML文件。 我的模型类包括内部类。
public class mymodel
{
private const string dec= "declaration",
abc="declaration";
[XmlElement("Item1", Namespace = dec)]
public string Item1{ get; set; }
[XmlRoot("InnerClass", Namespace = dec)]
public class InnerClass
{
[XmlElement("InnerItem", Namespace = abc)]
public string InnerItem{ get; set; }
}
}
DataSet Ds =Get_DataSet_from_Query("Select * from something");
mymodel DpAdv = null;
mymodel InnerClass=null;
for (int i = 0; i < Ds.Tables[0].Rows.Count; i++)
{
DpAdv = new mymodel
{
Item1= Ds.Tables[0].Rows[i]["ID"].ToString(),
};
InnerClass= new mymodel.InnerClass
{
InnerItem= Ds.Tables[0].Rows[i]["ID"].ToString(),
};
}
ConvertXML(DpAdv);
内部课程项目数据不包括在内且缺失。
这是我的xml输出文件。缺少内部类数据。
<?xml version="1.0" encoding="utf-8"?>
<DespatchAdvice xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:dec="declaration" >
<dec:Item1>14126</cbc:ID>
</DespatchAdvice>
如何将包括内部类数据在内的所有数据添加到XML文件中。
答案 0 :(得分:0)
现在我已经明白了。我应该为内部类声明变量
[XmlElement( ElementName = "Item1", DataType = "string", Namespace = DEC)]
public InnerClass Item1{ get; set; }
答案 1 :(得分:-1)
也许您需要正确使用这些类?班级通常使用Pascal案例。 FWIW,我做得很快,没有在这里检查小问题...甚至没有编译。
public class Mymodel
{
// const normally are UPPERCASE
private const string DEC = "declaration";
private const string ABC= "declaration";
public class InnerClass
{
[XmlElement( ElementName = "InnerItem", typeof(string), Namespace = ABC)]
public string InnerItem { get; set; }
}
[XmlElement( ElementName = "Item1", DataType = "string", Namespace = DEC)]
public string Item1{ get; set; }
public Mymodel
{
}
public Mymodel(string item, InnerClass inner)
{
this.Item1 = item;
this.InnerClass = inner;
}
}
类使用:
DataSet ds = Get_DataSet_from_Query("Select * from something");
List<Mymodel> dpAdvs = new List<Mymodel>();
Mymodel dpAdv = null;
var table = ds.Tables[0];
foreach (DataRow dr in table.Rows)
{
Mymodel dpAdv = new Mymodel();
dpAdv.Item1 = dr["ID"].ToString();
dpAdv.InnerClass = new Mymodel.InnerClass();
dpAdv.InnerClass.InnerItem = dr["ID"].ToString(),
dpAdvs.Add(dpAdv);
}
// Define the root element
var serializer = new XmlSerializer(typeof(List<Mymodel>),
new XmlRootAttribute("Mymodels"));
// or use it like this
XElement xmlElements = new XElement("Mymodels", dpAdvs.Select(i => new XElement("dpAdv", i)));