首页 > 解决方案 > 如何将特定的 XElement 修改为 file.xml

问题描述

我正在使用 xml 和 c# wpf,我想搜索一个简单的文件 xml 并在每次找到它时修改一个特定的 XElement。而不是包含在该行中的内容,我想将我写的任何内容放入文本框中,实际代码就是这个,现在我只管理如何修改单个特定元素

private void Button_Click(object sender, RoutedEventArgs e)
    {
        string xmlFilePath = @"C:\Users\codroipomad\Desktop\slave\Test.xml";
        XDocument xdoc = XDocument.Load(xmlFilePath);
        XNamespace ns = "http://www.fruitauthority.fake";

        var elBanana = xdoc.Descendants()?.Elements(ns + "FruitName")?.Where(x => x.Value == "Banana")?.Ancestors(ns + "Fruit");

        var elColor = elBanana.Elements(ns + "FruitColor").FirstOrDefault();

        //check se il file esiste,se non esiste lo crea
        if (!File.Exists(xmlFilePath))
        {
            File.Create(xmlFilePath).Dispose();

            if (elColor != null)
            {
                elColor.Value = box.Text;
            }
        }
        //se il file esiste setta il colore con valore pari al valore della textbox
        else if (File.Exists(xmlFilePath))
        {
            if (elColor != null)
            {
                elColor.Value = box.Text;
            }
        }

        xdoc.Save(xmlFilePath);
    }

我正在使用的 xml 是这个(我已经像片段 html 一样插入它,因为我发现只有这种方式可以向你展示)

<?xml version="1.0" encoding="utf-8"?>
<FruitBasket xmlns="http://www.fruitauthority.fake">
  <Fruit>
    <FruitName>Banana</FruitName>
    <FruitColor>pinuzzo</FruitColor>
  </Fruit>
  <Fruit>
    <FruitName>Apple</FruitName>
    <FruitColor>Red</FruitColor>
  </Fruit>
  <Fruit>
    <FruitName>Banana</FruitName>
    <FruitColor>feffolo</FruitColor>
  </Fruit>
  <Fruit>
    <FruitName>Apple</FruitName>
    <FruitColor>Red</FruitColor>
  </Fruit>
  <Face>
    <Name>Banana</Name>
    <Eyes>feffolo</Eyes>
  </Face>
  <Face>
    <Name>Apple</Name>
    <Eyes>Red</Eyes>
  </Face>
</FruitBasket>

在这种情况下,我只想修改程序可以找到的所有 FruitColor

标签: c#xmlwpf

解决方案


因此,要将所有香蕉的颜色更新为黄色,请使用以下代码:

        string xmlFilePath = @"C:\Users\codroipomad\Desktop\slave\Test.xml";
        XDocument xdoc = XDocument.Load(xmlFilePath);
        XNamespace ns = "http://www.fruitauthority.fake";

        var elBanana = xdoc.Descendants()?.Elements(ns + "FruitName")?.Where(x => x.Value == "Banana")?.Ancestors(ns + "Fruit");

        foreach (var item in elBanana)
        {
            var elColor = item.Elements(ns + "FruitColor").FirstOrDefault();

            //check se il file esiste,se non esiste lo crea
            if (!File.Exists(xmlFilePath))
                File.Create(xmlFilePath).Dispose();

            if (elColor != null)
            {
                elColor.Value = "YELLOW";
            }

        }

        xdoc.Save(xmlFilePath);

推荐阅读