Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Serialization to String

Tags:

c#

xml

I'm trying to serialize an object into a string. Here is the code:

XmlSerializer xmlSerializer = new XmlSerializer(data.GetType());
StringWriter textWriter = new StringWriter();
xmlSerializer.Serialize(textWriter, data);
var xml = textWriter.ToString();

This works but "\r\n" are part of the string. I want to perform an XSLT transform with this string. That doesn't work because of the "\r\n" characters.

Here is the transform code:

XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(xsltPath);

using (XmlReader xmlReader = System.Xml.XmlReader.Create(new StringReader(xmlString)))
{
     transform.Transform(xmlReader, xmlWriter);
     ...
}

How to I go about this?

like image 275
Gerson Avatar asked Aug 23 '26 07:08

Gerson


1 Answers

Simply replace those \r\ns with \n then use XSLT

var xml = textWriter.ToString().Replace("\r\n", "\n");
like image 141
Hossein Narimani Rad Avatar answered Aug 24 '26 22:08

Hossein Narimani Rad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!