开发者

How to replace CRLF with a space?

How can I parse out undesireabl开发者_运维问答e characters from a collection of data?

I am working with existing VB.NET code for a Windows Application that uses StreamWriter and Serializer to output an XML document of transaction data. Code below.

Private TransactionFile As ProjectSchema.TransactionFile
Dim Serializer As New Xml.Serialization.XmlSerializer(GetType    (ProjectSchema.TransactionFile))
Dim Writer As TextWriter
Dim FilePath As String
Writer = New StreamWriter(FilePath)
Serializer.Serialize(Writer, TransactionFile)
Writer.Close()

The XML document is being uploaded to another application that does not accept "crlf".

The "TransactionFile" is a collection of data in a Class named ProjectSchema.TransactionFile. It contains various data types. There are 5 functions to create nodes that contribute to the creation of a Master Transaction file named TransactionFile

I need to find CRLF characters in the collection of data and replace the CRLF characters with a space.

I am able to replace illegal characters at the field level with:

.Name = Regex.Replace((Mid(CustomerName.Name, 1, 30)), "[^A-Za-z0-9\-/]", " ")

But I need to scrub the entire collection of data.

If I try:

TransactionFile = Regex.Replace(TransactionFile, "[^A-Za-z0-9\-/]", " ")

Because TransactionFile cannot be converted to String I get a "Conversion from type 'Transaction' to type 'String' is not valid" message.

Bottom Line = How can I replace CRLF with a space when it shows up in TransactionFile data?


Don't do it this way. Create the serializer with XmlWriter.Create(). Which has an overload that accepts an XmlWriterSettings object. Which has lots of options to format the generated XML. Like NewLineChars, it lets you set the characters to use for a line end.


As Hans says, mess around with the XmlWriterSettings.

The next best choice is to write the file, then read the file into an xml object and process it element by element. This would let you remove crlf from within individual elements, but leave the ones between elements alone, for example.

Another possibility - rather than write directly to the file, you can make an intermediate string, and do a replace in that:

        Dim ms As New MemoryStream
        Serializer.Serialize(ms, TransactionFile)

        ms.Flush()
        ms.Position = 0

        Dim sr As New StreamReader(ms)
        Dim xmlString As String = sr.ReadToEnd

        sr.Close() ' also closes underlying memorystream

Then you could do your regex replace on the xmlString before writing it to a file. This should get all the crlf pairs, both within elements and between.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜