少しお役に立てば幸いです。XMLファイルに書き込もうとしていますが、XMLファイルに書き込むメソッドを書くのに苦労しています。これは手動で作成された XML ファイルです (Notepad++ などを使用):
<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>
アプリケーションのこの部分の目的は、GUI を使用してそれを記述することです。
アプリケーションで、ユーザーは XML ファイルの名前を選択します。その後、ユーザーがどこに保存したいか尋ねられるまで、一時フォルダーに保存されます。目的のファイル名を入力して [作成] をクリックすると、「createAndLoadXML」というメソッドが実行されます。その名前が示すように、XML ファイルを作成してから読み込みます (フォーム上のリストビュー コントロールを設定するため)。コードは以下で見ることができます。
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 を使用してルート要素 (ソフトウェア) 内に書き込む方法がわかりません。