Как изменить элемент в xml файле - C#
Формулировка задачи:
XML
Моя попытка
Пишет:
Как тогда?
<?xml version="1.0" encoding="utf-8"?>
<head>
<item id="0">
<name>Name1</name>
<surname>Surname1</surname>
<age>Age1</age>
<otchestvo>otchestvo1</otchestvo>
</item>
<item id="1">
<name>Name2</name>
<surname>Surname2</surname>
<age>Age2</age>
<otchestvo>otchestvo2</otchestvo>
</item>
<item id="2">
<name>Name3</name>
<surname>Surname3</surname>
<age>Age3</age>
<otchestvo>otchestvo3</otchestvo>
</item>
<item id="3">
<name>Name4</name>
<surname>Surname4</surname>
<age>Age4</age>
<otchestvo>otchestvo4</otchestvo>
</item>
</head>
private void button3_Click(object sender, EventArgs e)
{
int index = listBox1.SelectedIndex;
XDocument xDocument = XDocument.Load(@"C:\Users\Admin\Documents\Visual Studio 2010\Projects\TEST\TEST\XMLFile1.xml");
xDocument.Root.Element("item id=\"" + index.ToString() + "\"").Element("name").Value = textBox1.Text;
xDocument.Save(@"C:\Users\Admin\Documents\Visual Studio 2010\Projects\TEST\TEST\XMLFile1.xml");
}
Знак " ", шестнадцатеричное значение 0x20, не может использоваться в именах.
Решение задачи: «Как изменить элемент в xml файле»
textual
Листинг программы
string path = @"C:\Users\Admin\Documents\Visual Studio 2010\Projects\TEST\TEST\XMLFile1.xml";
int index = listBox1.SelectedIndex;
XDocument xDoc = XDocument.Load(path);
xDoc.Root.Elements("item").Where(el => el.Attribute("id").Value == index.ToString())
.Select(el => el.Element("name"))
.FirstOrDefault().SetValue(textBox1.Text);
xDoc.Save(path);