Reda
Reda

Reputation: 468

Adding Attributes to XML file Linq C#

I wanna add a Test (common) attribute to all my XML files. So that I could use it as a common attribute when I wanna test them.

I tried CreateAttribute but Linq dosen't recognize it

I tried "xElement.Add(new XAttribute("Test", value));" but it also didn't work Any Suggestions?

Thanks

Here for example is a code

    public void updateXmlFile(string strFileName)
    {
        XDocument oXDoc = XDocument.Load(strFileName);
        XElement oDcElement = oXDoc.Root.FirstNode as XElement;

        //Generate a Unique String to replace the original attribute value
        string newValue = GetUniqueKey();

        //oDcElement.Add(new XAttribute("Test", newValue)); /*NullReferenceException*/

        oDcElement.Attribute("Remark").Value = newValue; //This changes only the Remark Attribute
        oXDoc.Save(strFileName);                         //which isn't available in all XMLs

    }

I wanna add an additional, common value to the XMLs I pass through this method and give it a random value

My goal is to be able to make changes on an XML then compare it against the original copy in another folder

Upvotes: 2

Views: 3436

Answers (1)

PatrickSteele
PatrickSteele

Reputation: 14677

Use SetAttribute:

oDcElement.SetAttributeValue("Test", newValue);

Upvotes: 8

Related Questions