我对从文件中读取数据非常陌生,特别是xml文件。
我的bin\debug
文件夹中有一个xml文件,xml文件看起来像这样:
<Companies>
<Company>
<Name>Name1</Name><Code>11014</Code>
<MaintenancePercentage>15.9</MaintenancePercentage>
<Sales>
<Sale>
<Code>19538</Code>
<Title>ABC</Title>
<Date>2009-04-29T00:00:00</Date>
<Category>Category1</Category>
<Amount>6543.39</Amount>
</Sale>
<Sale>
<Code>19539</Code>
<Title>xyz</Title>
<Date>2009-04-30T00:00:00</Date>
<Category>Category2</Category>
<Amount>654.39</Amount>
</Sale>
</Sales>
</Company>
<Company>
<Name>Name1</Name><Code>11014</Code>
<MaintenancePercentage>15.9</MaintenancePercentage>
<Sales>
<Sale>
<Code>19538</Code>
<Title>ABC</Title>
<Date>2009-04-29T00:00:00</Date>
<Category>Category1</Category>
<Amount>6543.39</Amount>
</Sale>
<Sale>
<Code>19539</Code>
<Title>xyz</Title>
<Date>2009-04-30T00:00:00</Date>
<Category>Category2</Category>
<Amount>654.39</Amount>
</Sale>
</Sales>
</Company>
</Companies>
这是我的课程:
public class Company
{
public string Name;
public string Code;
public double MaintenancePercentage;
public double AverageSales;
public double TotalSales;
public double TotalMaintenanceFee;
public List<Sales> Saleses;
}
public class Sales
{
public string Code;
public string Title;
public DateTime DateTime;
public string Category;
public double Amount;
}
现在从xml文件中我想读取数据并存储它们。
如何读取xml文件中的值?
例如
var company = new Company();
company.Name = //name from xml file
//and so on
foreach(sales in company)
{
sales.code = //code from xml file
sales.title = //title from xml file
//and so on
}
这是我到目前为止使用谷歌的搜索结果所做的,但我不知道现在该做什么
var doc = new XmlDocument();
doc.Load(@"export.xml");
var root = doc.DocumentElement;
if (root == null)
{
return;
}
var company = root.SelectNodes("Company");
if (company == null)
{
return;
}
else
{
foreach (var companyData in company)
{
var title =
}
}
这最后一段代码至少有意义吗?
答案 0 :(得分:1)
定义一个Companies
类,其中只包含Company
的列表,然后您可以使用以下行中的代码将整批反序列化为您的对象集:
var serializer = new XmlSerializer(typeof(Companies));
var reader = new StreamReader(pathToXmlFile);
var companies = (Companies)serializer.Deserialize(reader);
reader.Close();
答案 1 :(得分:0)
假设您的Test.XML文件位于调试文件夹
var doc = (from e in XDocument.Load("Test.xml").Root.Elements("Company")
select new Company
{
name=(string)e.Element("name"),
MaintenancePercentage=(double)e.Element("MaintenancePercentage"),
Sales=(from sl in e.Elements("Sales").Elements("Sale")
select new Sals
{
Code=(string)sl.Element("Code"),
Title=(string)sl.Element("Title"),
Datetime=(DateTime)sl.Elemnt("Date"),
Category==(string)sl.Element("Category"),
Amount=(double)sl.Element("Amount")
}).ToArray()
}).ToList();
var company = new Company();
foreach(var Comp in doc)
{
company.name=Comp.name;
company.MaintenancePercentage=Comp.MaintenancePercentage;
}
var cSales=new Sales();
foreach(var salas in doc.Sales)
{
cSales.Code=salas.Code;
cSales.Title=salas.Title;
pcSales.DateTime=salas.Datetime;
cSales.Category=salas.Category;
cSales.Amount=salas.Amount;
}
我跳你得到你的解决方案......