locked
write into TEXT file using C# RRS feed

  • Question

  • I have an XML file - XMLFile3.xml

    <?xml version="1.0" standalone="yes" ?>
    - <DataSet1 xmlns="http://tempuri.org/DataSet1.xsd">
    - <MSH>
    <FieldSeparator>|</FieldSeparator>
    <EncodingCharacters>^~\$</EncodingCharacters>
    <SendingApplication>ADMIT</SendingApplication>
    <ReceivingApplication />
    <ReceivingFacility />
    <DateTimeOfMessage>200502110938</DateTimeOfMessage>
    <Security />
    <Message>ADT^A01</Message>
    <MessageControlID>00860</MessageControlID>
    <Processing>P</Processing>
    <Version>2.2</Version>
    <SequenceNumber />
    <ContinuationPointer />
    <AcceptAcknowledgmentType />
    <ApplicationAcknowledgmentType />
    <CountryCode />
    </MSH>
    </DataSet1>

    Using C# i need to
    Read the XML file, data by data and write these datas into the Text file( like - date.txt)    

    MSH|^~\$|ADMIT|CLAY COUNTY MEMORIAL|||200502110938||ADT^A01|00860|P|2.2||||||


    Tuesday, August 1, 2006 4:19 AM

Answers

  • how did you save the xml file? From a dataset? (theDataSet.WriteXml()) - if so ...

    try this:

     



    DataSet theDataSet = new DataSet();
    theDataSet.ReadXml(pathToXmlFile); //loads xml into dataset
     
    StreamWriter theWriter = new StreamWriter(Application.StartupPath + "\\test.txt");
     
    foreach (DataRow curRow in theDataSet.Tables[0].Rows)
    {
       foreach (object curObjectValue in curRow.ItemArray)
       {
          theWriter.Write(curObjectValue);
       }
    }
    theWriter.Close();
     

     

    Tuesday, August 1, 2006 5:20 AM
  • Here you go, here is the solution in VB.NET but it wouldn't be that hard to translate it into C#. I will even do it later (as I need it my self) and send you a copy if need.

    Public Sub XML_to_CSV(ByVal strFileName As String, ByVal strHeader As String, ByVal strOutput As String)

            ' Open an XML file
            Dim reader As XmlTextReader = New XmlTextReader(strFileName)
            ' This needs moving from this location to somewhere cleaner

            Dim doc As New XmlDocument() 'Define a new XmlDocument
            doc.Load(reader) ' Read in our XML file
            doc.PreserveWhitespace = True 'Make sure that we save all the white space (empty fields)
            Dim strRecord As String = "" ' Varible that we will store the record in.
            Dim objStreamReader As StreamReader
            'open the file
            objStreamReader = File.OpenText(strHeader)
            'Read the file storing it in the readfile string
            Dim readfile As String = objStreamReader.ReadToEnd()
            objStreamReader.Close()
            Dim fs As New FileStream(strOutput, FileMode.Create, FileAccess.Write)

            strRecord = readfile

            Dim s As New StreamWriter(fs)
            s.WriteLine(strRecord)
            strRecord = ""
            For Each clsRootNode As System.Xml.XmlNode In doc.ChildNodes
                If clsRootNode.NodeType = Xml.XmlNodeType.Element Then
                    For Each clsChildNode As System.Xml.XmlNode In clsRootNode.ChildNodes
                        'MessageBox.Show(clsChildNode.Name & ":" & clsChildNode.InnerText)
                        If clsChildNode.Name = "MSH" Then 'If we find a row
                            For Each clsItemNode As System.Xml.XmlNode In clsChildNode.ChildNodes
                                ' Process each of the records...
                                If clsItemNode.Name.Contains("date") Or clsItemNode.Name.Contains("Date") Then
                                    strRecord += Date.Parse(clsItemNode.InnerText).ToShortDateString + "|" 'Add a collumn
                                Else
                                    strRecord += clsItemNode.InnerText + "|" 'Add a collumn
                                End If

                            Next 'Next child
                            strRecord = strRecord.Substring(0, strRecord.Length - 1) 'Kill of the final comma
                            s.WriteLine(strRecord) 'Write the line to the file
                            strRecord = "" ' We have written to the file so kill it off
                        End If

                    Next
                End If
            Next
            reader.Close()
            s.Close()
        End Sub

    On the line ( strRecord += clsItemNode.InnerText + "|" 'Add a collumn ) is where your field divider is added. This is normally where the CSV comma would be but you can put what you like. It will need fitting to the XML schema you have but it should do what you want.
    Tuesday, August 1, 2006 8:48 AM

All replies

  • I guess you could maybe load it into a dataset, since looking at the top of the Xml file seems to have saved it from a dataset?

     

    then pretty much loop through each row/column and write to the textfile using the StreamWriter.

    here is a quick pseudo:

     

    foreach row in theDataSetTable

       foreach item in row.ItemArray

          writeToFile(item)

       end foreach

    end foreach

     

     

    Tuesday, August 1, 2006 4:51 AM
  • Plz Give me some sample codings that will be helpful:

    XmlTextReader tr = new XmlTextReader("c:/xml/XMLFile3.xml");

    Iam able to read the xml and not able to write it in the text file.



    Tuesday, August 1, 2006 5:04 AM
  • how did you save the xml file? From a dataset? (theDataSet.WriteXml()) - if so ...

    try this:

     



    DataSet theDataSet = new DataSet();
    theDataSet.ReadXml(pathToXmlFile); //loads xml into dataset
     
    StreamWriter theWriter = new StreamWriter(Application.StartupPath + "\\test.txt");
     
    foreach (DataRow curRow in theDataSet.Tables[0].Rows)
    {
       foreach (object curObjectValue in curRow.ItemArray)
       {
          theWriter.Write(curObjectValue);
       }
    }
    theWriter.Close();
     

     

    Tuesday, August 1, 2006 5:20 AM
  • Thanks for your valuable suggestions.

    MSH|^~\$|ADMIT|CLAY COUNTY MEMORIAL|||200502110938||ADT^A01|00860|P|2.2||||||

    How can i pass these delimiters to the below text file ?.

    |^~\$ADMIT200502110938ADT^A0100860P2.2
    Tuesday, August 1, 2006 5:34 AM
  • do you mean after writing everything to the textfile?

    if this is the case, then just before we close the StreamWriter (theWriter), we just write that:

     

    theWriter.Write("|^~\$ADMIT200502110938ADT^A0100860P2.2");

    theWriter.Close();

     

    does this help?

    Tuesday, August 1, 2006 5:46 AM
  • I have an XML file - XMLFile3.xml

    <?xml version="1.0" standalone="yes" ?>
    - <DataSet1 xmlns="http://tempuri.org/DataSet1.xsd">
    - <MSH>
    <FieldSeparator>|</FieldSeparator>
    <EncodingCharacters>^~\$</EncodingCharacters>
    <SendingApplication>ADMIT</SendingApplication>
    <ReceivingApplication /> --------------------------------------------------[ | ]
    <ReceivingFacility /> --------------------------------------------------[ | ]
    <DateTimeOfMessage>200502110938</DateTimeOfMessage>
    <Security />
    <Message>ADT^A01</Message>
    <MessageControlID>00860</MessageControlID>
    <Processing>P</Processing>
    <Version>2.2</Version>
    <SequenceNumber /> --------------------------------------------------[ | ]
    <ContinuationPointer /> --------------------------------------------------[ | ]
    <AcceptAcknowledgmentType /> --------------------------------------------------[ | ]
    <ApplicationAcknowledgmentType />--------------------------------------------------[ | ]
    <CountryCode /> --------------------------------------------------[ | ]
    </MSH>
    </DataSet1>


    Now iam getting the text value like this

    |^~\$ADMIT200502110938ADT^A0100860P2.2

    Now i want to pass this
    | to the data having null values.


    for example:

    SendingApplication>ADMIT</SendingApplication>
    <ReceivingApplication /> --------------------------------------------------[ | ]
    <ReceivingFacility /> --------------------------------------------------[ | ]
    <DateTimeOfMessage>200502110938</DateTimeOfMessage>

    ADMIT
    | | 200502110938

    MSH|^~\$|ADMIT|CLAY COUNTY MEMORIAL|||200502110938||ADT^A01|00860|P|2.2||||||


    Tuesday, August 1, 2006 6:31 AM
  • Here you go, here is the solution in VB.NET but it wouldn't be that hard to translate it into C#. I will even do it later (as I need it my self) and send you a copy if need.

    Public Sub XML_to_CSV(ByVal strFileName As String, ByVal strHeader As String, ByVal strOutput As String)

            ' Open an XML file
            Dim reader As XmlTextReader = New XmlTextReader(strFileName)
            ' This needs moving from this location to somewhere cleaner

            Dim doc As New XmlDocument() 'Define a new XmlDocument
            doc.Load(reader) ' Read in our XML file
            doc.PreserveWhitespace = True 'Make sure that we save all the white space (empty fields)
            Dim strRecord As String = "" ' Varible that we will store the record in.
            Dim objStreamReader As StreamReader
            'open the file
            objStreamReader = File.OpenText(strHeader)
            'Read the file storing it in the readfile string
            Dim readfile As String = objStreamReader.ReadToEnd()
            objStreamReader.Close()
            Dim fs As New FileStream(strOutput, FileMode.Create, FileAccess.Write)

            strRecord = readfile

            Dim s As New StreamWriter(fs)
            s.WriteLine(strRecord)
            strRecord = ""
            For Each clsRootNode As System.Xml.XmlNode In doc.ChildNodes
                If clsRootNode.NodeType = Xml.XmlNodeType.Element Then
                    For Each clsChildNode As System.Xml.XmlNode In clsRootNode.ChildNodes
                        'MessageBox.Show(clsChildNode.Name & ":" & clsChildNode.InnerText)
                        If clsChildNode.Name = "MSH" Then 'If we find a row
                            For Each clsItemNode As System.Xml.XmlNode In clsChildNode.ChildNodes
                                ' Process each of the records...
                                If clsItemNode.Name.Contains("date") Or clsItemNode.Name.Contains("Date") Then
                                    strRecord += Date.Parse(clsItemNode.InnerText).ToShortDateString + "|" 'Add a collumn
                                Else
                                    strRecord += clsItemNode.InnerText + "|" 'Add a collumn
                                End If

                            Next 'Next child
                            strRecord = strRecord.Substring(0, strRecord.Length - 1) 'Kill of the final comma
                            s.WriteLine(strRecord) 'Write the line to the file
                            strRecord = "" ' We have written to the file so kill it off
                        End If

                    Next
                End If
            Next
            reader.Close()
            s.Close()
        End Sub

    On the line ( strRecord += clsItemNode.InnerText + "|" 'Add a collumn ) is where your field divider is added. This is normally where the CSV comma would be but you can put what you like. It will need fitting to the XML schema you have but it should do what you want.
    Tuesday, August 1, 2006 8:48 AM
  • Thanks for ahmedilyas and devstuff. Now it's working.  Thanks all.

    With regards,
    Simha
    Tuesday, August 1, 2006 9:09 AM
  • hi...

    simhamoorthy

    i ma new to here, i reading xml file but not able to write into .text file

    m using c# please help me how to write into text file

    thanka

    Thursday, March 13, 2008 10:43 AM
  • This thread is over a year old, and simhamoorthy hasn't been active for more than a year either...
    Thursday, March 13, 2008 11:42 AM
  •  

    As this post is marked as answered you might be better off starting a new thread and referencing anything in this thread that relates to your problem.

     

    Thursday, March 13, 2008 11:53 AM
  • hello devstuff,

    Can u send me the C# code for the above VB code for xml to text conversion.

    Also, how are you handling tables?
    Friday, June 13, 2008 10:23 AM