Reputation: 3685
hi i have a question to linq to xml ...
i have a xml file with Title value:
my xml:
<?xml version="1.0" encoding="utf-8"?>
<Titles>
<values id="de">
<value value="Herr" display="Herr"></value>
<value value="Frau" display="Frau"></value>
</values>
<values id="cs">
<value value="Herr" display="Pan"></value>
<value value="Frau" display="Paní"></value>
</values>
<values id="en">
<value value="Herr" display="Mr."></value>
<value value="Frau" display="Mrs."></value>
</values>
<values id="es">
<value value="Herr" display="Sr."></value>
<value value="Frau" display="Sra."></value>
</values>
<values id="zh">
<value value="Herr" display="先生"></value>
<value value="Frau" display="女士"></value>
</values>
</Titles>
and I have a DropDownList:
<td><asp:DropDownList ID="drp_GuestListViewAddDialog_GuestTitle" runat="server"></asp:DropDownList></td>
here is my c# code:
XDocument x = XDocument.Load(Server.MapPath(@"~\App_Data\DropDown\Title.xml"));
string data = (from item in x.Elements("Titles").Elements("values") where item.Attribute("id").Value == "de" select item.Attribute("display").Value).First();
UPDATE:
For Example if I want the id = "de" I want this
<values id="de">
<value value="Herr" display="Herr"></value>
<value value="Frau" display="Frau"></value>
</values>
Upvotes: 1
Views: 612
Reputation: 16733
var results = doc.Descendants("values")
.Where(e => (string)e.Attribute("id") == "zh")
.SelectMany(e => e.Elements("value"))
.Select(v => new { Value = v.Attribute("value").Value, Text = v.Attribute("display").Value })
.ToList();
Then bind it:
drp_GuestListViewAddDialog_GuestTitle.Enabled = true;
drp_GuestListViewAddDialog_GuestTitle.DataSource = result;
drp_GuestListViewAddDialog_GuestTitle.DataBind();
Sorry, I can't check it to see if it compiles, I'm winging it here.
Upvotes: 1
Reputation: 191
EDIT: this works...
var x = XDocument.Load(@"~\App_Data\DropDown\Title.xml");
var list = x.Descendants("values")
.Where(el => el.Attribute("id").Value == "de")
.Descendants("value")
.Select(el => new
{
value = el.Attribute("value").Value,
display = el.Attribute("display").Value
)
.ToList();
drp_GuestListViewAddDialog_GuestTitle.DataValueField = "value";
drp_GuestListViewAddDialog_GuestTitle.DataTextField = "display";
drp_GuestListViewAddDialog_GuestTitle.DataSource = list;
drp_GuestListViewAddDialog_GuestTitle.DataBind();
Upvotes: 1