クエリを次のように変更しました。
var query = from user in main.Root.Descendants("country")
where user.Elements("state").Any() && user.Elements("state").First().Value == st
select user;
ルート要素の子孫を取得し、国の状態要素が存在することを確認してから、指定された値で状態値を確認することに注意してください。一致が見つかった場合、その国の要素が選択されます。
また、これは XMlelements を返します。それらを に直接バインドすることはできません。DataSource
そのクエリから国名などを選択し、最終的にリストまたは配列に変換できます。上記の結果は、DropDownList に直接バインドできます
サンプルxmlは次のとおりです。
<?xml version="1.0" encoding="utf-8" ?>
<countries>
<country>Test1</country>
<country name ="A">
<state>Test2</state>
</country>
<country name ="B">
<state>Test2</state>
</country>
<country name ="C">
<state>Test3</state>
</country>
</countries>
xml を読み込む
XDocument main = XDocument.Load("input.xml");
国要素属性から国名を取得
var countryNames = (from user in main.Root.Descendants("country")
where user.Elements("state").Any() && user.Elements("state").First().Value == "Test2"
select user.Attribute("name").Value).ToList();
編集:
あなたのXML:
<country>
<name>India</name>
<state>
<text>Maharashtra</text>
<text>Kashmir</text>
<text>Goa</text>
</state>
</country>
更新されたコード:
var countryNames = (from user in main.Descendants("country")
where user.Elements("state").Descendants("text").Any(s => s.Value == st)
select user.Element("name").Value).ToList();