Reputation: 9623
I have a xml file like this
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfOffice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Offices>
<Office>
<OfficeId>5</OfficeId>
<OfficeName>NewOne1</OfficeName>
<City>Mehsana1</City>
<Country>India1</Country>
</Office>
<Office>
<OfficeId>8</OfficeId>
<OfficeName>NewOne</OfficeName>
<City>Mehsna1</City>
<Country>Country</Country>
</Office>
<Office>
<OfficeId>9</OfficeId>
<OfficeName>Nataraj</OfficeName>
<City>Mehsana</City>
<Country>India</Country>
</Office>
<Office>
<OfficeId>10</OfficeId>
<OfficeName>Nere1</OfficeName>
<City>Nere1</City>
<Country>USA1</Country>
</Office>
<Office>
<OfficeId>11</OfficeId>
<OfficeName>Nataraj</OfficeName>
<City>Mehsana</City>
<Country>India</Country>
</Office>
<Office>
<OfficeId>15</OfficeId>
<OfficeName>Nere1</OfficeName>
<City>Nere1</City>
<Country>USA1</Country>
</Office>
</Offices>
</ArrayOfOffice>
Now I want to add an attribute in <Offices>
Tag like <Offices Multi="Y">..........</Offices>
How can I set this Multi="Y"
in Offices
Node using C#? Do I have to edit the xml File and save back to that xml file?
Thanks.
Upvotes: 0
Views: 288
Reputation: 1038940
You could use a XDocument to load the XML file, add the Multi
attribute to the Offices
tag and save it back:
var doc = XDocument.Load("test.xml");
var offices = doc.Element("ArrayOfOffice").Element("Offices");
offices.Add(new XAttribute("Multi", "Y"));
doc.Save("test.xml");
Or with a XmlDocument if you are using an older version than .NET 3.5:
var doc = new XmlDocument();
doc.Load("test.xml");
var offices = doc.DocumentElement.SelectSingleNode("Offices");
var multi = doc.CreateAttribute("Multi");
multi.Value = "Y";
offices.Attributes.Append(multi);
doc.Save("test.xml");
Upvotes: 1