C# 向现有 XMLNode 添加属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13637611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:17:11  来源:igfitidea点击:

Adding attribute to existing XMLNodes

c#xmlxml-parsing

提问by Nistor Alexandru

Hi I am trying to add an attribut to several tags in an existing xml file.Here is the xml structure:

嗨,我正在尝试向现有 xml 文件中的多个标签添加一个属性。这是 xml 结构:

<Planet>
  <Continent ContinentName="Africa">
    <Country CountryName="Algeria" />
    <Country CountryName="Angola" />
     ...
  </Continent>
  <Continent ContinentName="Europe">
    <Country CountryName="France" />
    <Country CountryName="England" />
    ...
  </Continent>
  ...
</Planet>

I am trying to add an Id attribut to each of the country tags.Here is my code:

我正在尝试为每个国家/地区标签添加一个 Id 属性。这是我的代码:

public static List<Cities> cities = new List<Cities>();

XmlDocument xDoc = new XmlDocument();
xDoc.Load(@"D:\Projects IDE\Visual Studio\Tutorial\e-commerce\classModeling\GenerateXml file\GenerateXml file\bin\Debug\Planet.xml");
XmlAttribute xKey = xDoc.CreateAttribute("Id");
XmlElement root = xDoc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//Country");
int count = 0;

foreach( XmlNode node in nodes ) {
    string name = node.Attributes["CountryName"].Value;

    foreach (var cityObj in cities)
    {
        xKey.Value = cityObj.cityInitial;

        if(name == cityObj.cityName)
        {
            count++;
            node.Attributes.Append(xKey);
            Console.WriteLine(count);
        }
    }

}

xDoc.Save(@"D:\Projects IDE\Visual Studio\Tutorial\e-commerce\classModeling\GenerateXml file\GenerateXml file\bin\Debug\Planets.xml");

The problems is that this code only adds the id to the last element in the XML file. Now at first I tought that's because only one condition is true but then I added a counter and it turns out that that condition is true 179 times.If that is the case why am I getting only one attributt added at the finish?

问题是这段代码只将 id 添加到 XML 文件中的最后一个元素。现在起初我认为这是因为只有一个条件为真,但后来我添加了一个计数器,结果该条件为真 179 次。如果是这样,为什么我在结束时只添加了一个属性?

采纳答案by Teddy

You should place XmlAttribute xKey = xDoc.CreateAttribute("Id");inside the loop

你应该放在XmlAttribute xKey = xDoc.CreateAttribute("Id");循环里面