[英]Reading and Writing Data to XML
我已經修改了這個項目已有一段時間了,我遇到了一堵磚牆。 這是我的第一個項目,我真的不確定從這里去哪里。 我正在盡力閱讀下一步的內容,這樣就不必再在這里發帖了,但是看來我別無選擇。
無論如何,這是我要在此項目中完成的簡短說明。 我試圖從已經存在的XML文檔中的三個元素中檢索某些值。 在將每個元素的每個值加載到其各自的文本框中后,然后嘗試將對這些值的任何更改保存到文檔中。 (說起來容易做!)
我正在使用XDocument將值存儲到列表中,然后將其顯示在其文本框中。
我不知道如何將更改更新回原始值並保存。 到目前為止,嘗試進行保存會給我留下空白的XML文檔,並使我的應用程序崩潰。 :\\
這是我可以讀取和顯示的XML數據:
<client>
<endpoint address="http://127.0.0.1:8086">
<endpoint address="http://127.0.0.1:8084">
<endpoint address="net.tcp://127.0.0.1:8085">
</client>
這是到目前為止我編寫的一些代碼。
OpenFileDialog AgentConfig = new OpenFileDialog();
private void button1_Click(object sender, EventArgs e)
{
AgentConfig.Filter = "Agent.exe.config (*.config)|*.config";
if (AgentConfig.ShowDialog() == DialogResult.OK)
{
textBox1.Text = AgentConfig.FileName;
}
var addresses = XDocument.Load(AgentConfig.FileName)
.Descendants("endpoint")
.Select(x => (string)x.Attribute("address"))
.ToList();
textBox2.Text = addresses[0];
textBox3.Text = addresses[1];
textBox4.Text = addresses[2];
if (textBox2.Text != addresses[0])
{
addresses[0] = textBox2.Text;
}
if (textBox3.Text != addresses[1])
{
addresses[1] = textBox3.Text;
}
if (textBox4.Text != addresses[2])
{
addresses[3] = textBox4.Text;
}
}
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog SF = new SaveFileDialog();
if (SF.ShowDialog() == DialogResult.OK)
{
}
}
任何幫助將不勝感激。
提前致謝!
var xElem = new XElement("client",
new XElement("endpoint", new XAttribute("address", textBox2.Text)),
new XElement("endpoint", new XAttribute("address", textBox3.Text)),
new XElement("endpoint", new XAttribute("address", textBox4.Text)));
xElem.Save(filename);
一種方法是使用以下類:
class System.Data.DataSet
表示內存中的數據緩存,請參閱文檔
class System.IO.StramWriter
實現TextWriter以特定的編碼將字符寫入流,請參見文檔
然后像這樣去:
DataSet ds = newDataSet();
CreateMyDataSet("your arguments"); // Create your DataSet according to your xml-format
StreamWriter sw = new StreamWriter(SaveFileDialog.FileName, ...);
sw.Write(ds.GetXml()); // GetXml() returns the xml representation of your data
sw.Close();
嘗試使用Xml編寫器保存。 這是你的鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.