Reputation: 357
How can I declare a variable inside a for loop
foreach (System.Xml.XmlNode xmlnode in node)
{
string AMSListName = xmlnode.Attributes["Title"].Value.ToString();
/* the below assignment should be variable for each iteration */
XmlNode ndViewFields + AMSListName = xmlDoc.CreateNode(XmlNodeType.Element,
"ViewFields", "");
}
How do I achieve this? I want for each value in the for loop to have the xmlnode to have a different name. Is this possible at all?
Upvotes: 0
Views: 277
Reputation: 460108
Use a collection:
List<XmlNode> nodes = new List<XmlNode>();
foreach (System.Xml.XmlNode xmlnode in node)
{
string AMSListName = xmlnode.Attributes["Title"].Value.ToString();
nodes.Add(xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", ""));
}
You can access this list via index or in a loop:
foreach(var node in nodes)
{
// ...
}
another approach If the name is an identifier, use a Dictionary
:
Dictionary<string, System.Xml.XmlNode> nodeNames = new Dictionary<string, System.Xml.XmlNode>();
foreach (System.Xml.XmlNode xmlnode in node)
{
string AMSListName = xmlnode.Attributes["Title"].Value.ToString();
nodeNames[AMSListName] = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
}
This will replace an already available node with a given name, otherwise it'll add it.
You can access it via name:
XmlNode node
if(nodeNames.TryGetValue("Some Name", out node)
{
// ..
};
Upvotes: 5
Reputation: 125
I would suggest using something like a dictionary or hastable. Because even if you did create dynamic variables, how would you reference them later? I am not sure this is possible.
Hashtable ViewFields = new Hashtable();
foreach (System.Xml.XmlNode xmlnode in node)
{
string AMSListName = xmlnode.Attributes["Title"].Value.ToString();
XmlNode nd = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
ViewFields.Add(AMSListName,nd);
}
Upvotes: 0