![](/img/trans.png)
[英]XElement.Load(“~/App_Data/file.xml”) Could not find a part of the path
[英]How to modify a specific XElement into a file.xml
I'm playing with xml and c# wpf, i want to search through a simple file xml and modify a specific XElement every time i found it. 而不是包含在该行中的内容,我想将我写的任何内容放入文本框中,实际代码就是这个,现在我只管理如何修改单个特定元素
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
因此,要将所有香蕉的颜色更新为黄色,请使用以下代码:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.