0

我有一个这样的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"OfficesNode 中设置它?我是否必须编辑 xml 文件并保存回该 xml 文件?

谢谢。

4

1 回答 1

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");
于 2012-05-21T11:00:52.737 回答