nhat
nhat

Reputation: 1169

XML output to text file?

I'm trying to output a specific node to output to a text file(output to console fine) but I keep getting an error message: 'System.Xml.XmlNodeList' to 'string[]' on this line:

string[] lines = elemList;

Here is some more code:

namespace countC
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("list.xml");

            XmlElement root = doc.DocumentElement;
            XmlNodeList elemList = root.GetElementsByTagName("version");
            for (int i = 0; i < elemList.Count; i++)
            {
                Console.WriteLine(elemList[i].InnerXml);
                string[] lines = elemList;
                System.IO.File.WriteAllLines(@"C:\VBtest\STIGapp.txt", lines);
            }
            Console.ReadKey();
        } 
    }
}

Upvotes: 0

Views: 345

Answers (2)

Justin
Justin

Reputation: 86779

The error is because you are trying to assign an object of type XmlNodeList to a variable of type string[] - the two are incompatible and you can't assign one from the other.

If you do this instead then it will at least compile:

string line = elemList[i].InnerXml;
System.IO.File.WriteAllText(@"C:\VBtest\STIGapp.txt", line);

Although I'm not sure that it will do what you want (if elemList contains more that one element the above will keep overwriting the given file).

Upvotes: 2

Russ Clarke
Russ Clarke

Reputation: 17909

elemList is an XmlNodeList, you can't implicitly cast it to a string array.

You could try this

string line = elemList[i].InnerText;
System.IO.File.WriteAllLines(@"C:\VBtest\STIGapp.txt", line);

but this of course, depends on your data.

Upvotes: 1

Related Questions