简体   繁体   中英

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!

有几种方法可以实现此目的,但最简单的方法是对XNode.ToString使用重载,您可以在其中指定SaveOptions

doc.ToString(SaveOptions.DisableFormatting);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM