具有包含汽车收藏的XML:
<?xml version="1.0" encoding="utf-8"?>
<CarCollection>
<Cars>
<Car>
<StockNumber>1020</StockNumber>
<Make>Nissan</Make>
<Model>Sentra</Model>
</Car>
<Car>
<StockNumber>1010</StockNumber>
<Make>Toyota</Make>
<Model>Corolla</Model>
</Car>
<Car>
<StockNumber>1111</StockNumber>
<Make>Honda</Make>
<Model>Accord</Model>
</Car>
<Car>
<StockNumber>2000</StockNumber>
<Make>Maybach</Make>
<Model>S 600</Model>
</Car>
<Car>
<StockNumber>2001</StockNumber>
<Make>Ferrari</Make>
<Model>F355 Spider</Model>
</Car>
</Cars>
</CarCollection>
及其反序列化的对象类,它们是由xsd.exe生成的:
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Xml.Serialization;
//
// Dieser Quellcode wurde automatisch generiert von xsd, Version=4.6.1055.0.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class CarCollection : object, System.ComponentModel.INotifyPropertyChanged {
private CarCollectionCars[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Cars", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public CarCollectionCars[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
this.RaisePropertyChanged("Items");
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class CarCollectionCars : object, System.ComponentModel.INotifyPropertyChanged {
private CarCollectionCarsCar[] carField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Car", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public CarCollectionCarsCar[] Car {
get {
return this.carField;
}
set {
this.carField = value;
this.RaisePropertyChanged("Car");
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class CarCollectionCarsCar : object, System.ComponentModel.INotifyPropertyChanged {
private string stockNumberField;
private string makeField;
private string modelField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string StockNumber {
get {
return this.stockNumberField;
}
set {
this.stockNumberField = value;
this.RaisePropertyChanged("StockNumber");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Make {
get {
return this.makeField;
}
set {
this.makeField = value;
this.RaisePropertyChanged("Make");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Model {
get {
return this.modelField;
}
set {
this.modelField = value;
this.RaisePropertyChanged("Model");
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
我想查询StockNumber,Make和Car类的Model。因此, 我从以下代码开始:
XmlSerializer ser = new XmlSerializer(typeof(CarCollection));
CarCollection cars;
using (XmlReader reader = XmlReader.Create(file))
{
cars = (CarCollection)ser.Deserialize(reader);
foreach (var item in cars.Items)
{
foreach (var carCollection in item.Car)
{
carPool.Add(new CarPool()
{
Make = carCollection.Make,
Model = carCollection.Model,
StockNumber = carCollection.StockNumber
});
}
}
}
但是,我不喜欢嵌套嵌套循环。有人知道如何使用LINQ来更有效地查询吗?
答案 0 :(得分:2)
如果要解析XML,并且使用XmlSerializer
,则需要管理类层次结构及其繁琐的工作来管理复杂和大型xml的类层次结构
所以一种选择是使用XDocument
。
您只需在XDocument
上使用LINQ即可从XML中获取所需的数据。
通过使用XDocument
,您可以直接集中精力处理数据,而无需管理类结构。
XDocument xdoc = XDocument.Load(@"Path to your xml file");
var result = (from car in xdoc.Descendants("Car")
select new
{
StockNumber = car.Element("StockNumber")?.Value,
Make = car.Element("Make")?.Value,
Model = car.Element("Model")?.Value
}).ToList();
Console.WriteLine("StockNumber\tMake\t\tModel");
Console.WriteLine("----------------------------------------------");
foreach (var item in result)
{
Console.WriteLine(item.StockNumber + "\t\t" + item.Make + "\t\t" + item.Model); ;
}
替代:
仍然要使用XmlSerializer
反序列化xml,然后下面的类是类结构,
[XmlRoot("Car")]
public class Car
{
[XmlElement("StockNumber")]
public string StockNumber { get; set; }
[XmlElement("Make")]
public string Make { get; set; }
[XmlElement("Model")]
public string Model { get; set; }
}
[XmlRoot("Cars")]
public class Cars
{
[XmlElement("Car")]
public List<Car> Car { get; set; }
}
[XmlRoot("CarCollection")]
public class CarCollection
{
[XmlElement("Cars")]
public Cars Cars { get; set; }
}
用法:
XmlSerializer ser = new XmlSerializer(typeof(CarCollection));
CarCollection cars = null;
using (StreamReader reader = new StreamReader(@"Path to your xml file"))
{
cars = (CarCollection)ser.Deserialize(reader);
}
List<Car> result = cars.Cars.Car.ToList();
//--------------------------Print the result to console--------------
Console.WriteLine("StockNumber\tMake\t\tModel");
Console.WriteLine("----------------------------------------------");
foreach (var item in result)
{
Console.WriteLine(item.StockNumber + "\t\t" + item.Make + "\t\t" + item.Model); ;
}
Console.ReadLine();
输出:
答案 1 :(得分:2)
Linq和SelectMany()应该解决嵌套循环:
// not tested or compiled
using (XmlReader reader = XmlReader.Create(file))
{
var cars = (CarCollection)ser.Deserialize(reader);
carPool.AddRange(
cars.Items.SelectMany(it => it.Car).Select(c =>
new CarPool()
{
Make = c.Make,
Model = c.Model,
StockNumber = c.StockNumber
}) );
}