0

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!

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Thx for your coment. I will use it in return whole document. But is there way to use it in concat?
Not exactly, you should project your sequence of elements to a sequence of strings: ...Elements().Select(x => x.ToString(SaveOptions.DisableFormatting)).
@StasPetrov Since it's a method of a base XNode class, you can use it inside the concat like string result = string.Concat(data.Select(e => e.ToString(SaveOptions.DisableFormatting)));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.