Change xml attribute in foreach statement c#
Posted
by
user1913479
on Stack Overflow
See other posts from Stack Overflow
or by user1913479
Published on 2012-12-18T16:36:37Z
Indexed on
2012/12/18
17:03 UTC
Read the original article
Hit count: 156
I need to save XML-attribute value in a database, using information if checkbox is checked. If checkbox is checked, the attribute value is "TRUE", otherwise it's false. When I use foreach statement, the last enumerated value is usually assigned.
Here is the part of my code:
XmlAttribute xmlAttribute = xmlDoc.CreateAttribute("BooleanValue");
foreach (string value in list) //list is a List<object>
{
XmlNode xmlNode = xmlDoc.CreateNode(XmlNodeType.Element, "VALUE", "");
if (checkBox1.Checked ||
checkBox2.Checked ||
checkBox3.Checked)
xmlAttribute.Value = "TRUE";
if (!checkBox1.Checked ||
!checkBox2.Checked ||
!checkBox3.Checked)
xmlAttribute.Value = "FALSE";
xmlNode.Attributes.Append(xmlAttribute);
xmlNode.InnerText = val;
childNode.AppendChild(xmlNode);
}
When I run my application, I get an XML attribute xmlAttribute "FALSE" value anyway.
What I need to have: I need to have the following XML:
<ROOT><NODE><VALUE ATTRIBUTE="TRUE">Value 1</VALUE></NODE>
<NODE><VALUE ATTRIBUTE="TRUE">Value 2</VALUE></NODE>
<NODE><VALUE ATTRIBUTE="FALSE">Value 3</VALUE></NODE>
<NODE><VALUE ATTRIBUTE="FALSE">Value 4</VALUE></NODE>
<NODE><VALUE ATTRIBUTE="TRUE">Value 5</VALUE></NODE>
<NODE><VALUE ATTRIBUTE="FALSE">Value 6</VALUE></NODE>
</ROOT>
What I actually get:
<ROOT><NODE><VALUE ATTRIBUTE="FALSE">Value 1</VALUE></NODE>
<NODE><VALUE ATTRIBUTE="FALSE">Value 2</VALUE></NODE>
<NODE><VALUE ATTRIBUTE="FALSE">Value 3</VALUE></NODE>
<NODE><VALUE ATTRIBUTE="FALSE">Value 4</VALUE></NODE>
<NODE><VALUE ATTRIBUTE="FALSE">Value 5</VALUE></NODE>
<NODE><VALUE ATTRIBUTE="FALSE">Value 6</VALUE></NODE>
</ROOT>
Because in C# FALSE value is stayed at last position in foreach loop
The question is: how do I do to assign the correct values of my attribute. Thanks
© Stack Overflow or respective owner