I want to create an XmlAttributeCollection and add some attributes depending on conditions. This is what I've tried.
XmlElement fishElement = doc.CreateElement(string.Empty, "fi", string.Empty);
XmlAttributeCollection attCollection = AddExtraAttributes(doc,condition);
foreach (XmlAttribute attribute in attCollection)
{
fishElement.Attributes.Append((XmlAttribute)attribute.Clone());
}
private XmlAttributeCollection AddExtraAttributes(XmlDocument doc,bool condition)
{
XmlAttributeCollection xmlAttributeCollection;
if(condition)
{
XmlAttribute attribute = doc.CreateAttribute("A");
attribute.Value = "value1";
xmlAttributeCollection.Append(attribute);
}
else
{
XmlAttribute attribute = doc.CreateAttribute("B");
attribute.Value = "value2";
xmlAttributeCollection.Append(attribute);
}
return xmlAttributeCollection;
}
But this way, I encounter this error:
xmlAttributeCollection might not be initialized before accessing
And if i try to do this:
XmlAttributeCollection xmlAttributeCollection = new XmlAttributeCollection;
It says:
Cannot access internal constructor 'XmlAttributeCollection' here
So how can I make it works?
Update
So I've solved the problem this way
XmlAttribute newAttr = doc.CreateAttribute("genre");
newAttr.Value = "novel";
XmlAttributeCollection attrColl = doc.DocumentElement.Attributes;
attrColl.Append(newAttr);
But now everytime I call AddExtraAttributes
, xmlAttributeCollection
has some extra attributes and I can't set it to null (xmlAttributeCollection=null
) before I run my method again. because then I can't run xmlAttributeCollection.append
.
So How can I reset xmlAttributeCollection
before adding attributes to it all over again?
I found a solution here
I don't know if there's a better one out there.
Update
As a solution for my second problem I used a list of
XmlAttribute
s so that I can create a new instance everytime I call the method. Now the whole code looks like this: