使用XDocument写入XML,但知道在哪里写

希望你能帮到我一点。 我正在尝试写一个XML文件,但我正在努力编写这个方法,并写入XML文件。 这是手动编写的XML文件(使用Notepad ++等):

    

这部分应用程序的目的是使用GUI编写它。

在应用程序中,用户选择XML文件的名称。 然后将其保存在临时文件夹中,直到有人询问用户要保存的位置为止。 输入所需的文件名并单击“创建”后,将运行名为“createAndLoadXML”的方法。 顾名思义,它会创建并加载XML文件(以填充表单上的listview控件)。 代码如下所示。

 private void createAndLoadXML() { // Method to create XML file based on name entered by user string tempPath = Path.GetTempPath(); string configFileName = fileNameTextBox.Text; string configPath = tempPath + configFileName + ".xml"; // Create XDocument XDocument document = new XDocument( new XDeclaration("1.0", "utf8", "yes"), new XComment("This XML file defines the software selections for use with the Software Installer"), new XComment("XML file generated by Software Installer"), new XElement("software", new XElement("software_entry", new XAttribute("name", ""), new XAttribute("path", ""), new XAttribute("type", ""), new XAttribute("switches", "")) ) ); document.Save(configPath); configCreateLabel.Visible = true; document = XDocument.Load(configPath); } 

现在,在此表单的下方是4个用于用户输入的文本框,每个文本框与创建的属性(名称,路径,类型和开关)相关。想法是用户将在这些文本框中写入,单击“添加”按钮然后程序会将这4个字段作为属性写入此XML文件。 到目前为止,我有这个代码,它非常不完整,甚至不使用LINQ to XML。

 private void writeToXML() { // Method to write lines to XML file based on user input // Sets string variables string fileName = softwareNameTextBox.Text; string filePath = filePathTextBox.Text; string fileType = installerType.Text.ToString(); string installSwitches = installSwitchesTextBox.Text; using (XmlWriter xw = XmlWriter.Load(configPath)) //This line is wrong, I know { xw.WriteStartElement("software"); xw.WriteElementString("name", fileName); xw.WriteElementString("path", filePath); xw.WriteElementString("type", fileType); xw.WriteElementString("switches", installSwitches); xw.WriteEndElement(); } } 

基本上,任何人都可以帮我用上面的方法向XML写入用户输入到文本框控件中的数据吗? 我不确定如何加载以前创建的XML文档(来自我的createAndLoadXML方法),以及如何使用LINQ to XML在根元素(软件)中编写。

试试吧。 我认为这应该可以为您提供所需的XML,因为您在此方法之前调用了createAndLoadXML 。 我在NotePad ++中写了这个,所以我可能会有一两个错误。

 private void writeToXML() { // Method to write lines to XML file based on user input // Sets string variables string fileName = softwareNameTextBox.Text; string filePath = filePathTextBox.Text; string fileType = installerType.Text.ToString(); string installSwitches = installSwitchesTextBox.Text; string FILE_PATH = "bla.xml"; XDocument xDoc = XDocument.Load(FILE_PATH); xDoc.Root.Add(new XElement("software_entry", new XAttribute("name", fileName), new XAttribute("path", filePath), new XAttribute("type", fileType), new XAttribute("switches", installSwitches) )); xDoc.Save(FILE_PATH); }