Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I am checking XML for attribute ProductCount under ProductDetails node, and if the attribute is not present add the attribute with a default value under this node.

I am able to check if the attribute exists or not but I am not able to add it, though it does not give me any error but does not even add the attribiute.

here is my code:

XDocument XMLDoc = XDocument.Load(fileName);

foreach (var detail in XMLDoc.Descendants(_ns + "ProductDetails"))
{
   if (detail.Attribute("ProductCount") == null)
   {
       detail.SetAttributeValue("ProductCount", "1");
   }
}


<productdetails hadsuspension="false" iscomplimentary="false" hasfamily1="false" hasfamily2="false" isinsured="false" hasjoint="false" />


_ns has my namespace

I am not able to figure out what I am doing wrong, why is it not adding ProductCount attribute if it does not exist.
Posted

1 solution

Hi,

SetAtttribute won´t create a new attribute for the XElement. It will just change the value of the specified attribute.

You can try creating this way -

detail.Add(new XAttribute("ProductCount", 1));


The above will create a new ProductCount attribute for the detail XElement. You should also save the xml after you add the new attribute.
Hope this helps.

Edit - BobJanova is right, SetAttributeValye does create a new attribute.
 
Share this answer
 
v4
Comments
BobJanova 12-Jul-11 6:47am    
It will, at least on XmlElement, because that's how I'm setting attributes in my code and it works fine. I think not saving the document might be the issue here.
ShonaR 12-Jul-11 6:55am    
Can you please paste some of you working code , what I might be missing. Thanks for your help.
Tarun.K.S 12-Jul-11 6:59am    
What you might be missing is that you are not saving your xml. XMLDoc.Save(fileName) will do the job.
And its working fine here also.
ShonaR 12-Jul-11 7:05am    
Thanks a lot, yup I missed saving it.
Tarun.K.S 12-Jul-11 6:58am    
Exactly, OP needs to save the XML.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900