Я хочу, чтобы linq сохранил мой xml в csv, и у меня проблема o.Проблема с linq-to-xml
Этот кронштейн здесь beacuse без него этот код не отображается (почему?)
<results>
<Countries country="Albania">
<Regions region="Centralna Albania">
<Provinces province="Durres i okolice">
<Cities city="Durres" cityCode="2B66E0ACFAEF78734E3AF1194BFA6F8DEC4C5760">
<IndividualFlagsWithForObjects Status="1" />
<IndividualFlagsWithForObjects Status="0" />
<IndividualFlagsWithForObjects magazyn="2" />
</Cities>
</Provinces>
</Regions>
</Countries>
<Countries country="Albania">
<Regions region="Centralna Albania">
<Provinces province="Durres i okolice">
<Cities city="Durres" cityCode="2B66E0ACFAEF78734E3AF1194BFA6F8DEC4C5760">
<IndividualFlagsWithForObjects storage="0" Status="1" />
<IndividualFlagsWithForObjects storage="1" Status="0" />
<IndividualFlagsWithForObjects storage="2" Status="1" />
</Cities>
</Provinces>
</Regions>
</Countries>
</results>
я должен отметить одну важную вещь: родительский узел , но когда я использую его loaded.Descendants (» результаты ") это ничего не дает.
XDocument loaded = XDocument.Load(@"c:\citiesxml.xml");
// create a writer and open the file
TextWriter tw = new StreamWriter("c:\\XmltoCSV.txt");
// Query the data and write out a subset of contacts
var contacts = (from c in loaded.Descendants("Countries")
select new
{
Country = (string)c.Attribute("ountry").Value,
Region = (string)c.Element("Regions").Attribute("region").Value,
Province= c.Element("Regions").Element("Provinces").Attribute("prowincja").Value,
City= c.Element("Regions").Element("Provinces").Element("Cities").Attribute("city").Value,
Kod = c.Element("Regions").Element("Provinces").Element("Cities").Attribute("cityCode").Value,
IndywidualnaFlagaStatus = c.Element("Regions").Element("Provinces").Element("Cities").Element("IndividualFlagsWithForObjects").Attribute("Status"),
IndywidualnaFlagaWartosc = c.Element("Regions").Element("Provinces").Element("Cities").Element("IndividualFlagsWithForObjects").Attribute("storage")
}).ToList();
последняя проблема:
IndywidualnaFlagaWartosc = c.Element("Regions").Element("Provinces").Element("Cities").Element("IndividualFlagsWithForObjects").Attribute("storage")
дает мне:
IndywidualnaFlagaWartosc = {storage="0"} (I see this while debugging)
Вы получаете ошибку, потому что значение равно null для элементов. Вам нужно использовать .Attribute (""), чтобы получить атрибуты и использовать значение. – Stephan
Не могли бы вы разместить лучшее подмножество вашего xml-файла, чтобы мы могли попробовать и дать вам ответ? Конечно, Стефан прав, вам нужно использовать метод Attribute (""), но вам также нужно проверить, является ли результат нулевым, прежде чем получить значение, поэтому исключение вашей ссылки на объект ... –