1

DDL で国名を選択した場合、ある DDL に別の DDL を入力しています。対応する州は、以下の別の DDL に表示される必要があります。私のコードは次のとおりです。

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    string  st = (DropDownList1.SelectedIndex).ToString();

    XDocument main = XDocument.Load((Server.MapPath(@"XMLFile1.xml")));

    var query = from user in main.Descendants("country")
                 where st == user.Element("state").Value
                 select user;

    DropDownList2.DataSource = query;
    DropDownList2.DataBind();

}

しかし、別の DDL に状態を入力することができません。だれかがこれを手伝ってくれますか?

4

2 に答える 2

1

クエリを次のように変更しました。

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();
于 2012-06-05T04:19:37.567 に答える
0

代わりにこれを使用してください:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
     string  st = DropDownList1.SelectedValue;

     XDocument main = XDocument.Load((Server.MapPath(@"XMLFile1.xml")));


    var query = from user in main.Descendants("country")
                 where st == user.Element("state").Value
                 select user;

    DropDownList2.DataSource = query;
    DropDownList2.DataBind();

}

値ではなくアイテムのインデックス (1/2/3/4/5) を使用していました。そのアイテムのインデックスではなく値 (表示メンバー) を使用するように変更しました。

于 2012-06-05T03:36:02.680 に答える