在xml中插入新元素之前,检查值是否存在

本文关键字:检查 存在 是否 元素 xml 插入 新元素 | 更新日期: 2023-09-27 18:14:00

下面有一个xml文件,格式如下:

<?xml version="1.0" encoding="utf-8" ?>
<Root>
<Countries>
    <country>India</country>
    <country>USA</country>  
    <country>UK</country>      
</Countries>
</Root>
string newCountry="UAE"

我想将这个"UAE"国家插入到上面的xml文件中,在此之前我想检查"UAE"是否已经存在于xml中。如果不存在则只需要插入,否则不进行操作。我该怎么做呢?

在xml中插入新元素之前,检查值是否存在

像这样:

XDocument xml = XDocument.Load("path_to_file");
string newCountry = "UAE";
XElement countries = xml.Descendants("Countries").First();
XElement el = countries.Elements().FirstOrDefault(x => x.Value == newCountry);
if (el == null)
{
    el = new XElement("country");
    el.Value = newCountry;
    countries.Add(el);        
}
//Console.WriteLine(countries.ToString());

最简单的方法可能是将xml读入c#对象,检查是否存在UAE,可能的话添加它,然后将对象写回xml。