【问题标题】:LINQ To Xml how to generate xml without formattingLINQ To Xml如何在不格式化的情况下生成xml
【发布时间】:2016-09-26 10:39:47
【问题描述】:

有没有办法使用 linq to xml 生成 xml,无需任何格式(空格、换行符等)且无需保存到文件,只在内存中?

我将此 xml 发送到某个 api,这是要求。现在我正在使用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("  ", "");

感谢您的帮助!

【问题讨论】:

    标签: c# xml linq linq-to-xml


    【解决方案1】:

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

    doc.ToString(SaveOptions.DisableFormatting);
    

    【讨论】:

    • 感谢您的评论。我将使用它作为回报整个文档。但是有没有办法在 concat 中使用它?
    • 不完全是,您应该将元素序列投影到字符串序列:...Elements().Select(x => x.ToString(SaveOptions.DisableFormatting))
    • @StasPetrov 因为它是XNode 基类的方法,所以你可以像string result = string.Concat(data.Select(e => e.ToString(SaveOptions.DisableFormatting))); 一样在concat 中使用它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    相关资源
    最近更新 更多