LINQ to XML 在标签之间生成\r\n? [英] LINQ to XML generates \r\n between tags?

查看:38
本文介绍了LINQ to XML 在标签之间生成\r\n?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在生成一个具有这种结构的 XElement:

I am generating a XElement having this structure:

<TestNames>\r\n <Test>YA</Test>\r\n <Test>YO</Test>\r\n </TestNames>

如何以非 hack 的方式去除空格和 \r\n :)

How do I get rid of the whitespaces and \r\n in a non-hack way :)

更新:

XElement testsXmlDocument= new XElement("TestNames");           

foreach (string test in selectedTests)         
    testsXmlDocument.Add(new XElement("Test",test)); 

return testsXmlDocument.ToString();

推荐答案

XElement 提供了 ToString 接受 SaveOptions 类型的参数.此枚举的值之一是 DisableFormatting.

XElement provides an overload of ToString that takes an argument of type SaveOptions. One of the values of this enumeration is DisableFormatting.

如果这不能给您足够的控制权,那么您需要使用 XElement 的 Save 重载,它采用 XmlWriter.可以使用 XmlWriterSettings 控制 XmlWriter 的输出.

If this doesn't give you enough control then you need to use the Save overload of XElement that takes an instance of XmlWriter. The output of an XmlWriter can be controlled by using XmlWriterSettings.

请注意,创建 XmlWriter 的推荐方法是使用静态 创建 方法而不是直接构造一个方法.如果您想要字符串中的输出,您可以使用采用 StringWriter.

Note that the recommended way of creating an XmlWriter is to use the static Create method instead of constructing one directly. If you wantthe output in a string, you can use the overload that takes a StringWriter.

这篇关于LINQ to XML 在标签之间生成\r\n?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆