我想通過linq保存我的xml在csv中,我有問題。linq-to-xml問題
這個支架在這裏怎麼一回事,因爲沒有它,這個代碼不顯示(爲什麼?)
<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)
您會收到錯誤,因爲元素上的值爲空。您需要使用.Attribute(「」)來獲取屬性並在其上使用Value。 – Stephan 2010-05-07 12:53:22
您可以發佈您的XML文件的更好的子集,以便我們可以嘗試並給你一個測試的答案? 當然斯蒂芬是正確的,你需要使用Attribute(「」)方法,但你也需要測試結果是否爲null之前獲取該值,因此您的對象引用異常... – 2010-05-07 12:54:32