Hope you can help me a bit. I'm trying to write to an XML file, but I'm struggling to write a method that, well, writes to an XML file. This is an XML file written by hand (using Notepad ++, etc.):
<software>
<software_entry
name="Adobe Acrobat X Standard"
path="Applications\Acrobat\Acrobat X Standard\AcroStan.msi"
type="msi"
switches="/qn ALLUSERS=1"
/>
<software_entry
name="Adobe Acrobat X Professional"
path="Applications\Acrobat\Acrobat X Pro\AcroPro.msi"
type="msi"
switches="/qn ALLUSERS=1"
/>
</software>
The purpose of this part of the application is to write this using the GUI.
In the application, the user selects the XML file name. Then it is saved in the temp folder until the user asks where they would like to save it. After entering the desired file name and clicking the Create button, the createAndLoadXML method is launched. As the name implies, it creates and then loads the XML file (to populate the list control on the form). The code can be seen below.
private void createAndLoadXML()
{
string tempPath = Path.GetTempPath();
string configFileName = fileNameTextBox.Text;
string configPath = tempPath + configFileName + ".xml";
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()
{
string fileName = softwareNameTextBox.Text;
string filePath = filePathTextBox.Text;
string fileType = installerType.Text.ToString();
string installSwitches = installSwitchesTextBox.Text;
using (XmlWriter xw = XmlWriter.Load(configPath))
{
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.