Stas Petrov Stas Petrov - 2 months ago 20
C# Question

LINQ To Xml how to generate xml without formatting

Is there way to generate xml using linq to xml without any formatting (whitespaces, newlines etc.) and without saving to file, just in memory?

I am sending this xml to some api, and this is requirements. Now i am using

string.Replace();


var doc = new XDocument(
new XDeclaration("1.0", "UTF-8", null),
new XElement("request",
new XAttribute("version", "1.0"),
new XElement("m",
new XElement("id", credentials.id),
new XElement("signature"), ""),
new XElement("data",
new XElement("p",
new XAttribute("id", ""),
new XElement("porp",
new XAttribute("name", "c"),
new XAttribute("value", c)),
new XElement("porp",
new XAttribute("name", "a"),
new XAttribute("value", a))))));


var data = doc.Element("request").Element("data").Elements();
string result = string.Concat(data).Trim().Replace("\r\n", "").Replace(" ", "");
var signature = Utils.ComputeSignature(result, credentials.Password);
doc.Element("request").Element("m").Element("signature").Value = signature;
return doc.ToString().Trim().Replace("\r\n", "").Replace(" ", "");


Thanks for any help!

Answer

There are a few ways to achieve this, but the easiest is to use the overload for XNode.ToString where you can specify your SaveOptions:

doc.ToString(SaveOptions.DisableFormatting);