简体   繁体   中英

How can I set an attribute of node in XML file in c#

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM