1

I am creating a dynamic form where a user selects an area then a topic, then based on the topic a set of controls will load. The options for the form are all defined in an XML file.

My issues is that when I am traversing the XML I am getting down to the defined controls which I have 2 in the text file I made it is creating each control twice. I think it would be better to show some code then explain so here is my code.

 <?xml version="1.0" encoding="utf-8" ?>
 <options>
  <option name="xerox">
   <sub_option name="Paper Jam">
    <input type="dropdown" name="location" />
    <input type="textbox" name="printername" />
   </sub_option>
   <sub_option name="New Printer Request" />
   <sub_option name="Supply Request" />
   <sub_option name="Hardware Failure" />
 </option>
</options> 

And the C# code below

 protected void loadControls(string parent, string parentNode)
    {
        XmlDocument itemList = new XmlDocument();
        itemList.Load(@"c:\inetpub\wwwroot\sp\css\itemList.xml");
        Panel controls = new Panel();
        XmlNodeList nodeList = itemList.SelectNodes("options/child::node()");
        test.Text = parent;
        foreach (XmlNode node in nodeList)
        {
            if (node.Attributes["name"].Value == parentNode && node.HasChildNodes)
            {
                test.Text = "for 2 coming";
                foreach (XmlNode subnode in node.ChildNodes)
                {
                    if (subnode.Attributes["name"].Value == parent && subnode.HasChildNodes)
                    {
                        foreach (XmlNode optionNode in subnode.ChildNodes)
                        {

                            string controlType = optionNode.Attributes["type"].Value;
                            string controlName = optionNode.Attributes["name"].Value;
                            switch(controlType)
                            {
                                case "dropdown":
                                    DropDownList ddl = new DropDownList();
                                    qna.Controls.Add(ddl);
                                    break;
                                case "textbox":
                                    TextBox tb = new TextBox();
                                    qna.Controls.Add(tb);
                                    break;       
                            }

                        }
                    }
                }
            }


        }

Output below(this is after selecting Paper Jam) output

4

1 回答 1

1

I guess the issue is in your below code lines:

test.Text = "for 2 coming";
foreach (XmlNode subnode in node.ChildNodes)
{

You should check the following instead of foreach loop here

if(node.ChildNodes.Count>0)
{
  ...
}
于 2013-01-10T09:29:41.283 回答