使用LINQ获取xml文件中元素的值

时间:2017-04-16 13:00:48

标签: c# xml linq

我有一个简单的角色创建样式表单,用户可以将其名称输入到文本框中,它将存储在名为“playername”的字符串中。在玩家输入他们的名字后,他们可以按下保存按钮,这将弹出一个SaveFileDialog,其中玩家名字符串使用XElement保存到XML文件中。如果用户退出游戏并再次启动它们,则可以按下加载按钮,名称的XML值内的值应覆盖当前名称。我似乎无法从XML文档中获取值并使用LINQ覆盖字符串。提前谢谢。

<Character>
  <Basicinfo>
    <Name>bob</Name>
  </Basicinfo>
</Character>

代码:

string playername;

private void savebutton_Click(object sender, EventArgs e)
    {
        SaveFileDialog savefiledisplay = new SaveFileDialog();
        savefiledisplay.FileName = "temp";
        savefiledisplay.Filter = "XML File|*.xml";
        savefiledisplay.Title = "Save your game file";
        savefiledisplay.DefaultExt = "xml";

        if (savefiledisplay.ShowDialog() == DialogResult.OK)
        {
            XElement savefile = new XElement("Character",
                new XElement("Basicinfo",
                    new XElement("Name", playername)));
            savefile.Save(savefiledisplay.FileName);
        }
    }

private void loadbutton_Click(object sender, EventArgs e)
    {
        OpenFileDialog openfiledisplay = new OpenFileDialog(); //creates an open file dialog
        openfiledisplay.DefaultExt = "xml"; // default extension to look for
        openfiledisplay.Title = "Open your save file"; //title of the open file display
        openfiledisplay.Filter = "XML File|*.xml"; //filters for only xml files

        if (openfiledisplay.ShowDialog() == DialogResult.OK)
        {
            XElement loadsavefile = XElement.Load(openfiledisplay.FileName);
            //code for setting the playername string equal to the value inside the xml file
        }
    }

0 个答案:

没有答案