Lord-David
Lord-David

Reputation: 545

Read the data from XML file into flat files(txt) and with formated data

I have an XML file with nodes and data...I need to write that into a text file as normal data. The nodes being the headers of the data that follow.

EG XML:

<Bank>
<accountholder>Georgina Wax</accountholder>
<accountnumber>408999703657</accountnumber>
<accounttype>cheque</accounttype>
<bankname>National Bank</bankname>
<branch>Africa</branch>
<amount>2750.00</amount>
<date>12/01/2012</date>
</Bank>   

To txt file and formatted as :

accountholder accountnumber accounttype bankname
Georgina Wax 408999703657 cheque National Bank

I can't seem to have it to have spaces between the data and hearders.

Below is what I tried :

 StreamWriter writer = File.CreateText(@"C:\\Test.txt");
 XmlDocument doc = new XmlDocument();
 doc.Load(@"C:\\bank.xml");
       writer.WriteLine(string.Join("|",doc.SelectSingleNode("/debitorders/deduction").ChildNodes.C    ast<XmlElement>().Select(e =>    doc.SelectSingleNode("/debitorders/deduction/bankname").ToString())));

  foreach (XmlElement book in doc.SelectNodes("/debitorders/deduction"))
            {
                writer.WriteLine(book.ChildNodes.Cast<XmlElement>().Select(e =>    e.InnerText).ToArray());
            }

Please help.

Upvotes: 0

Views: 1842

Answers (2)

Sulaiman_J
Sulaiman_J

Reputation: 1

XDocument xdoc = new XDocument();
xdoc = XDocument.Load(fname);
xdoc.Save(fname1);

will save the file with the tags alignment formating

Upvotes: 0

Muhammad Umar
Muhammad Umar

Reputation: 3781

This will produce output like you want.

private static void LoadAndWriteXML()
    {
        string headerFiles = "";
        string values = "";
        using (XmlReader reader = XmlReader.Create(@"C:\\bank.xml"))
        {
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && !reader.Name.Equals("Bank"))   // we have to skip root node means bank node.
                {
                    headerFiles += reader.Name + " ";
                    values += reader.ReadString() + " ";
                }
            }
        }

        StreamWriter writer = new StreamWriter(@"C:\\Test.txt");

        writer.WriteLine(headerFiles.Trim());
        writer.WriteLine(values.Trim());

        writer.Close();


    }

Upvotes: 2

Related Questions