My second post in the same evening, apologies!
I have an XML file which contains several bits of information for various software entries (snippet seen below).
<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>
I am using LINQ to XML to load the XML file. In my application I have two listboxes, the first of which (listBox1) is populated with the names of each entry in this XML file. The user can then move these entries from one listbox to another (listBox2).
I am trying to write a method that iterates through each entry in listBox2, finds the matching entry in the XML file and then retrieves all of the other attributes for that entry. For example, a user has added Adobe Acrobat X Professional to the second listbox. The method should look through the XML file, find the entry with the attribute “name” that matches what is in the list, and write the other data (path, type, switches) or set them as the value of strings. So far, after much tweaking, I’ve achieved little. I managed to get some really garbled output.
My code so far is as follows.
private void writeBatchFile()
{
// Get temp folder location
string tempPath = Path.GetTempPath();
// Create batch file
using (StreamWriter writer = File.CreateText(tempPath + @"\swInstaller.cmd"))
{
// Loop through entries in listBox2
foreach (string item in listBox2.Items)
{
var dataFromXML = from data in document.Descendants("software_entry")
where data.Element("name").Value == item
select new
{
fileName = (string) data.Element("name"),
filePath = (string) data.Element("path"),
fileType = (string) data.Element("type"),
fileSwitches = (string) data.Element("switches")
};
// Write to batch file
writer.WriteLine(fileName + filePath + fileType + fileSwitches);
}
}
}
In the code I’ve got a foreach loop for the text values in listBox2. I’m then attempting to find where that value is equal to a “name” value in the XML, and then when it does, set the other attributes for that value to those strings (filePath for path, fileType for type etc.). Finally, I’m trying to write those strings to a text file. With this particular attempt, all I’m getting is 5 blank lines. Can anybody point me in the right direction as to what I’m doing wrong?
Thanks a lot.
You are trying to read XML attributes, not elements. Use the Attribute method instead:
You also need to make these additional changes:
dataFromXMLmay contain several elements and you would need to use a loop or index to access them.fileNameand other variables as members of thedataFromXMLvariable. There aren’t local variables of their own so that’s why you are getting the error message you mentioned.stringas values read from XML attributes are already strings by default.