0

我一直在修补这个项目一段时间,但我遇到了砖墙。这是我的第一个项目,我真的不知道从哪里开始。我正在尽最大努力阅读下一步是什么,这样我就不必再在这里发帖了,但似乎我别无选择。

无论如何,这里是关于我试图用这个项目完成什么的简要说明。我正在尝试从现有 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)
        {

        }
    }

任何帮助都将不胜感激。

提前致谢!

4

3 回答 3

1
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);
于 2013-08-19T06:46:31.107 回答
0

One approach could be to use the following classes:

class System.Data.DataSet 

Represents an in-memory cache of data, see documentation

class System.IO.StramWriter  

Implements a TextWriter for writing characters to a stream in a particular encoding, see documentation

Go then like this:

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();  
于 2013-08-19T06:41:17.247 回答
-1

尝试使用 Xml 编写器进行保存。这是你的链接

[链接] http://www.dotnetperls.com/xmlwriter

于 2013-08-19T06:38:31.380 回答