запись xml данных в файл .txt - PullRequest
0 голосов
/ 13 апреля 2020

Я хочу исправить .txt файл, для которого данные поступают из базы данных sql. Текст, который я хочу записать в файл .txt, представляет собой XML тип данных в sql.

Я получаю xml данные в текстовом файле, но он действует как одна строка. Я хочу, чтобы он выглядел как xml формат.

 Dim swRMSRequest As StreamWriter
 swRMSRequest = File.CreateText(strFileRMSRequest)
 swRMSRequest.WriteLine(dtRow("RMS_reqSentM"))
 swRMSRequest.Close()

Путь к файлу strFileRMSRequest. dtRow("RMS_reqSentM") выглядит следующим образом: enter image description here

Я хочу, чтобы мой текстовый файл выглядел как enter image description here

Ответы [ 3 ]

0 голосов
/ 13 апреля 2020

Вам нужно обработать ваш текстовый файл как XML. LINQ для XML - лучший API для этого.

VB. NET

Sub Main
    Dim strXMLFile As String = "e:\temp\temp.xml"
    Dim xmlDoc As XDocument = XDocument.Parse(dtRow("RMS_reqSentM").ToString)

    Dim Settings As New XmlWriterSettings()
    Settings.Indent = True            ' make it False if you want XML as one single line
    Settings.OmitXmlDeclaration = True  ' Suppress the xml header <?xml version="1.0" encoding="utf-8"?>
    Settings.Encoding = New System.Text.UTF8Encoding(False) ' The false means, do not emit the BOM.

    Dim Writer As XmlWriter = XmlWriter.Create(strXMLFile, Settings)

    xmlDoc.Save(Writer)
End Sub
0 голосов
/ 24 апреля 2020

Вот как мне это сделать. Надеюсь, это поможет другим.

Protected Sub GetTextFiles(ByVal strPath As String, ByVal strmessage As String, 
ByVal reqType As String)


    Try
        If (reqType = "XML") Then
            Dim swRMSRequest As StreamWriter
            Dim txtstr As String = String.Empty
            'swRMSRequest = File.CreateText(strFileRMSRequest)
            swRMSRequest = File.CreateText(strPath)
            Dim xmldoc As XmlDocument = New XmlDocument()
            'xmldoc.LoadXml(dtRow("RMS_reqSentM"))
            xmldoc.LoadXml(strmessage)
            Dim sb As New StringBuilder()
            ''`'We will use stringWriter to push the formated xml into our StringBuilder sb.`  
            Using stringWriter As New StringWriter(sb)
                '' `'We will use the Formatting of our xmlTextWriter to provide our indentation.`  
                Using xmlTextWriter As New XmlTextWriter(stringWriter)
                    xmlTextWriter.Formatting = Formatting.Indented
                    xmldoc.WriteTo(xmlTextWriter)
                End Using
                txtstr = sb.ToString()
            End Using
            swRMSRequest.WriteLine(txtstr)
            swRMSRequest.WriteLine(" ")
            swRMSRequest.Close()
        Else
            Dim swRMSRequest As StreamWriter
            Dim txtstr As String = strmessage
            swRMSRequest = File.CreateText(strPath)
            Dim sb As New StringBuilder()
            swRMSRequest.WriteLine(txtstr)
            swRMSRequest.WriteLine(" ")
            swRMSRequest.Close()
        End If


    Catch ex As Exception
        ex.Message.ToString()
    End Try
End Sub`
0 голосов
/ 13 апреля 2020

Поскольку вас беспокоит только XML единственной строки, используйте ExecuteScalar, чтобы получить только ваше значение RMS_reqSentM на основе некоторого условия (мой пример будет, когда PK соответствует значению). Как только вы получите свое значение, просто вызовите IO.File.WriteAllText, чтобы записать значение в текстовый файл.

'Declare the object that will be returned from the command
Dim xml As String

'Declare the connection object
Dim con As OleDbConnection

'Wrap code in Try/Catch
Try
    'Set the connection object to a new instance
    con = New SqlConnection()

    'Create a new instance of the command object
    'TODO: Change MyTable and MyTableId to valid values
    Using cmd As SqlCommand = New SqlCommand("SELECT RMS_reqSentM FROM MyTable WHERE MyTableId = @0;", con)
        'Paramterize the query
        'TODO: Change MyId to a valid value
        cmd.Parameters.AddWithValue("@0", MyId)

        'Open the connection
        con.Open()

        'Use ExecuteScalar to return a single value
        xml = cmd.ExecuteScalar()

        'Close the connection
        con.Close()
    End Using
Catch ex As Exception
    'Display the error
    Console.WriteLine(ex.Message)
Finally
    'Check if the connection object was initialized
    If con IsNot Nothing Then
        If con.State = ConnectionState.Open Then
            'Close the connection if it was left open(exception thrown)
            con.Close()
        End If

        'Dispose of the connection object
        con.Dispose()
    End If
End Try

If (Not String.IsNullOrWhitespace(xml)) Then
    'Write the XML to the text file
    IO.File.WriteAllText(strFileRMSRequest, xml)
End If
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...