Я пытаюсь найти способ сохранить данные обратно в xml файл с кодировкой "iso-8859-7".
сначала загружаю xml, используя
public XmlDocument LoadDocument(String x)
{
XmlDocument document = new XmlDocument();
StreamReader stream = new StreamReader(xml, Encoding.GetEncoding("iso-8859-7"));
document.Load(stream);
return (document);
}
для загрузки атрибутов внутри элементов управления формы, а затем при нажатии кнопки сохранения
private void savebtn_Click(object sender, EventArgs e)
{
XmlNodeList attributes = commonMethods.LoadDocument(xml).DocumentElement.SelectNodes("//Class[@Name='" + classname + "']/Property[@Id='" + id + "']/attribute::*");
for (int x = 0; x < attributes.Count; )
{
foreach (Control ctr in table1.Controls)
{
if (ctr is TextBox)
{
if (ctr.Text == attributes[x].Value.ToString()) { x++; }
else
{
attributes[x].Value = ctr.Text; commonMethods.SaveDocument(xml);
x++;
}
}
else if (ctr is ComboBox)
{
if (((ComboBox)ctr).Text == attributes[x].Value) { x++; }
else
{
attributes[x].Value = ((ComboBox)ctr).Text; commonMethods.SaveDocument(xml);
x++;
}
}
}
}
}
он сохраняет изменения обратно в xml файл. Я использовал его для сохранения без использования xmlwriter, такого как xmldoc.Save("sample.xml)
но из-за некоторых символов внутри файла мне пришлось использовать другой подход.
public XmlDocument SaveDocument(String x)
{
XmlDocument document = new XmlDocument();
StreamWriter stream = new StreamWriter(x,false,Encoding.GetEncoding("iso-8859-7"));
document.Save(xml);
return (document);
}
Проблема в том, что когда я компилирую его, он говорит: "xml используется другим процессом", и он терпит неудачу.
System.IO.IOException
У вас есть это исключение, потому что файл все еще открыт StreamReader, который ожидает завершения (сбор мусора). Вы всегда должны распоряжаться своими потоками (и читателями/писателями), чтобы как можно скорее освободить дескриптор файла.
public XmlDocument LoadDocument(String path)
{
XmlDocument document = new XmlDocument();
using (StreamReader stream = new StreamReader(path, Encoding.GetEncoding("iso-8859-7")))
{
document.Load(stream);
}
return (document);
}
public XmlDocument SaveDocument(XmlDocument document, String path)
{
using (StreamWriter stream = new StreamWriter(path,false,Encoding.GetEncoding("iso-8859-7")))
{
document.Save(stream);
}
return (document);
}
private void savebtn_Click(object sender, EventArgs e)
{
var doc = commonMethods.LoadDocument(xml);
XmlNodeList attributes = doc.DocumentElement.SelectNodes("//Class[@Name='" + classname + "']/Property[@Id='" + id + "']/attribute::*");
for (int x = 0; x < attributes.Count; )
{
foreach (Control ctr in table1.Controls)
{
if (ctr is TextBox)
{
if (ctr.Text == attributes[x].Value.ToString()) { x++; }
else
{
attributes[x].Value = ctr.Text; commonMethods.SaveDocument(doc, xml);
x++;
}
}
else if (ctr is ComboBox)
{
if (((ComboBox)ctr).Text == attributes[x].Value) { x++; }
else
{
attributes[x].Value = ((ComboBox)ctr).Text; commonMethods.SaveDocument(doc, xml);
x++;
}
}
}
}
}
Вы не утилизируйте StreamReader
объект после загрузки документа
добавьте инструкцию using
:
public XmlDocument LoadDocument(String x)
{
XmlDocument document = new XmlDocument();
using (StreamReader stream = new StreamReader(xml, Encoding.GetEncoding("iso-8859-7")))
{
document.Load(stream);
}
return (document);
}
ссылка: http://msdn.microsoft.com/en-us/library/system.io.streamreader(v=vs.110).aspx