[英]How to serialize my xml rows in to c# objects
我有示例xml
<ListingDoc version="1.0">
<Areas>
<Area Area_Seq="1" Area_Name="Mumbai" Area_Code="MUM"/>
<Area Area_Seq="1" Area_Name="Delhi" Area_Code="DEL"/>
</Areas>
<Companies>
<Company Company_Name="ABCD" Company_Rating="5" Company_Parent=""/>
<Company Company_Name="XYZ" Company_Rating="12" Company_Parent="ABCD"/>
<Company Company_Name="MAN" Company_Rating="77" Company_Parent=""/>
</Companies>
</ListingDoc>
我想使用C#在相應的對象中序列化該xml。 但是當我這樣做時,只有交替的行進入對象。 我用下面寫的代碼
XmlDataDocument xmldoc = new XmlDataDocument();
FileStream xmlFile=null;
xmlFile = new FileStream("c://temp//Listing.xml", FileMode.Open, FileAccess.Read);
using (xmlFile)
{
XmlNode n1= xmldoc.DocumentElement;
XmlNodeList nodes = n1.SelectNodes("Companies");
if (nodes != null && nodes.Count > 0)
{
//log session node found
XmlDataDocument companyXml= new XmlDataDocument();
companyXml.LoadXml(nodes[0].OuterXml);
XmlNode Tag_comp = companyXml.DocumentElement;
XmlReader xmlReader = new XmlNodeReader(Tag_comp);
List<Company> companyList=new List<Company>();
using (xmlReader)
{
while (xmlReader.Read())
{
if (xmlReader.AttributeCount > 0)
{
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(Company));
var session = (Company)ser.Deserialize(xmlReader);
companyList.Add(session);
}
}
}
}
}
這會用其他行填充我的列表。 請提出一些修復問題的建議,因為我發現序列化行時,xmlreader前進到下一條記錄,並且在while循環中也使用了xmlReader.Read()。
另外,我也嘗試使用XDocument。 但是它給我錯誤根元素丟失,所以建議我一些。
在我看來,您正在為自己做很多事。 讓框架一直為您處理XML到Object的轉換。
下面的示例使用一個自定義路徑(因此更改它),但是它確實假定您的XML結構。 這應該給您足夠的提示,讓您繼續前進。
class Program
{
const string filename = @".\Example.xml";
static void Main(string[] args)
{
XmlSerializer xSer = new XmlSerializer(typeof(ListingDoc), new Type[] { typeof(Company), typeof(Area) });
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
// load from disk into object model
ListingDoc listing = xSer.Deserialize(fs) as ListingDoc;
// output loaded info
listing.Areas.ForEach(area => Console.WriteLine("Area: {0}, {1}, {2}", area.Name, area.Sequence, area.Code));
listing.Companies.ForEach(company => Console.WriteLine("Companies: {0}, {1}, {2}", company.Name, company.Rating, company.Parent));
}
}
}
public class ListingDoc
{
public List<Area> Areas;
public List<Company> Companies;
}
public class Company
{
[XmlAttribute("Company_Rating")]
public int Rating;
[XmlAttribute("Company_Name")]
public string Name;
[XmlAttribute("Company_Parent")]
public string Parent;
}
public class Area {
[XmlAttribute("Area_Seq")]
public int Sequence;
[XmlAttribute("Area_Name")]
public string Name;
[XmlAttribute("Area_Code")]
public string Code;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.