如何在c#中设置XML文件中节点的属性

时间:2012-05-21 10:54:09

标签: c# xml

我有一个像这样的xml文件

<?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>

现在我想在<Offices>标记<Offices Multi="Y">..........</Offices>

中添加一个属性

如何使用C#在Multi="Y"节点中设置此Offices?我是否必须编辑xml文件并保存回该xml文件?

感谢。

1 个答案:

答案 0 :(得分:1)

您可以使用XDocument加载XML文件,将Multi属性添加到Offices标记并保存回来:

var doc = XDocument.Load("test.xml");
var offices = doc.Element("ArrayOfOffice").Element("Offices");
offices.Add(new XAttribute("Multi", "Y"));
doc.Save("test.xml");

如果您使用的是比.NET 3.5更旧的版本,则使用XmlDocument

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