Select the elements, of the first node of XML (linq,C#)
My question is often asked at several places, but I have an xml, without attributes, so I can't use those methods. My XML's structure is this:
<offers>
<offer>
<seller>
<citizen>
<name>A name</name>
<id>An ID</id>
</citizen>
</seller>
<amount>Number</amount>
<exchange-rate>Rate</exchange-rate>
</offer>
.
.
.
<offer>....
</offer>
</offers>
I managed to populate a multicolumn listview with this code:
var offers = from o in loaded.Elements("offers").Elements("offer") select o;
foreach (var vmi in offers)
开发者_Python百科 {
ListViewItem item = new ListViewItem();
item = lista1.Items.Add(vmi.Descendants("name").First().Value);
item.SubItems.Add(vmi.Element("amount").Value);
item.SubItems.Add(vmi.Element("exchange-rate").Value);
}
But now, I need to select data-s (name,amount,exchange-rate) between the first <offer></offer>
Could you please provide the code for this in C#? I tried the FirstNode, or the First() but I am stucked. Thank you in advance!
UPDATE! I forgot to mention that the citizen tag may varying in the xml. It is citizen or company. That's why I used the Descendants method. But if you can show me a better way, to handle this. I would appreciate it.
var firstOffer = loaded.Element("offers").Element("offer");
var name = firstOffer.Element("seller").Element("citizen").Element("name").Value;
var id = firstOffer.Element("seller").Element("citizen").Element("id").Value;
var amount = firstOffer.Element("amount").Value;
var exchangeRate = firstOffer.Element("exchange-rate").Value;
XElement xml = XElement.Load(xmlAddress);
var first = xml.Element("offer");
var name = first.Descendants("name").First().Value;
var amount = first.Element("amount").Value;
var exchangeRate = first.Element("exchange-rate").Value;
精彩评论