views:

30

answers:

2

How can I make a C# console program reads the attributes of an xml file then output it to a text file in the format: textbox.Settings.Keywords.Add("attribute") where attribute is the attribute. A sample of the xml file:

<Keywords>
...
<Keyword name = "if" />
<Keyword name = "else" />
...
</Keywords>
+2  A: 

Like this:

File.WriteAllLines( 
    XElement.Load(filename)
            .Descendants("Keyword")
            .Attributes("name")
            .Select(n => "textbox.Settings.Keywords.Add(\"" + n.Value + "\");")
            .ToArray()
    );
SLaks
+1, very nice; I need to give `XElement` a try someday...
Rubens Farias
A: 

Try this:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("...");

using(StreamWriter writer = new StreamWriter("yourfile.txt"))
foreach (XmlNode node in xmlDoc.SelectNodes("//Element/@*"))
{
    writer.WriteLine(
        String.Format("textbox.Settings.Keywords.Add(\"{0}\")",
            node.Name));
}
Rubens Farias