Значение атрибута и его количество в XML-файле - C#
Формулировка задачи:
Доброго времени суток!
Есть xml-документ
Нужно вывести города и количество отелей в каждом.
Делаю так, но выводит общее число отелей.
Как сделать так, чтобы было "Город : количество отелей"?
<?xml version="1.0" encoding="utf-8"?>
<root>
<hotel hname="Attica" hcountry="Greece" hcity="Athens">
<stars>5</stars>
<client>
<fio>Juliennes J.</fio>
<num>5</num>
<age>45</age>
<country>France</country>
<ofhotel>Attica</ofhotel>
</client>
</hotel>
<hotel hname="Electra" hcountry="Greece" hcity="Athens">
<stars>4</stars>
<client>
...
</client>
</hotel>
<hotel hname="Lozenge" hcountry="Spain" hcity="Madrid">
<stars>5</stars>
<client>
...
</client>
</hotel>
<hotel hname="Medplaya" hcountry="Spain" hcity="Barcelona">
<stars>3</stars>
<client>
...
</client>
</hotel>
</root>
XElement xe = XElement.Load("d:\\test.xml");
int res = (from s in xe.Descendants("hotel") select s).Count();
MessageBox.Show("Количество: " + res.ToString());Решение задачи: «Значение атрибута и его количество в XML-файле»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication10 {
class Program {
static void Main(string[] args) {
Root root = GetXmlRoot("test.xml");
var result = root.Hotel.GroupBy(h => h.Hcity).Select(n => new { City = n.Key, HotelCount = n.Count() });
foreach (var r in result) {
Console.WriteLine(r);
}
Console.ReadLine();
}
static Root GetXmlRoot(string path) {
if (!File.Exists(path)) {
return null;
}
using (Stream fs = File.OpenRead(path)) {
XmlSerializer xml = new XmlSerializer(typeof(Root));
Root root = (Root)xml.Deserialize(fs);
return root;
}
}
}
[XmlRoot(ElementName = "client")]
public class Client {
[XmlElement(ElementName = "fio")]
public string Fio { get; set; }
[XmlElement(ElementName = "num")]
public string Num { get; set; }
[XmlElement(ElementName = "age")]
public string Age { get; set; }
[XmlElement(ElementName = "country")]
public string Country { get; set; }
[XmlElement(ElementName = "ofhotel")]
public string Ofhotel { get; set; }
}
[XmlRoot(ElementName = "hotel")]
public class Hotel {
[XmlElement(ElementName = "stars")]
public string Stars { get; set; }
[XmlElement(ElementName = "client")]
public Client Client { get; set; }
[XmlAttribute(AttributeName = "hname")]
public string Hname { get; set; }
[XmlAttribute(AttributeName = "hcountry")]
public string Hcountry { get; set; }
[XmlAttribute(AttributeName = "hcity")]
public string Hcity { get; set; }
}
[XmlRoot(ElementName = "root")]
public class Root {
[XmlElement(ElementName = "hotel")]
public List<Hotel> Hotel { get; set; }
}
}