我想从c#编写一些HTML(html是一个示例,这可能是其他语言..)

例如:

    string div = @"<div class=""className"">
                      <span>Mon text</span>
                   </div>";


将产生:

<div class="className">
            <span>Mon text</span>
         </div>


从HTML的角度来看,这不是很酷...

正确的HTML缩进的唯一方法是像这样缩进C#代码:

            string div = @"<div class=""className"">
    <span>Mon text</span>
</div>";


我们得到正确缩进的HTML:

<div class="className">
    <span>Mon text</span>
</div>


但是像这样缩进C#确实破坏了代码的可读性...

有没有办法对C#语言的缩进进行处理?

如果不是,那么有人提供的小费要比:

string div = "<div class=\"className\">" + Environment.NewLine +
             "  <span>Mon text</span>" + Environment.NewLine +
             "</div>";


而且比

var sbDiv = new StringBuilder();
sbDiv.AppendLine("<div class=\"className\">");
sbDiv.AppendLine("    <span>Mon text</span>");
sbDiv.AppendLine("</div>");




我用什么作为解决方案:

非常感谢@Yotam的回答。

我写了一些扩展名以使对齐方式“动态”:

    /// <summary>
    /// Align a multiline string from the indentation of its first line
    /// </summary>
    /// <remarks>The </remarks>
    /// <param name="source">The string to align</param>
    /// <returns></returns>
    public static string AlignFromFirstLine(this string source)
    {
        if (String.IsNullOrEmpty(source)) {
            return source;
        }

        if (!source.StartsWith(Environment.NewLine)) {
            throw new FormatException("String must start with a NewLine character.");
        }

        int indentationSize = source.Skip(Environment.NewLine.Length)
                                .TakeWhile(Char.IsWhiteSpace)
                                .Count();

        string indentationStr = new string(' ', indentationSize);
        return source.TrimStart().Replace($"\n{indentationStr}", "\n");
    }


然后我可以像这样使用它:

private string GetHtml(string className)
{
    return $@"
            <div class=""{className}"">
                <span>Texte</span>
            </div>".AlignFromFirstLine();
}


返回正确的html:

<div class="myClassName">
    <span>Texte</span>
</div>


一个限制是它只能与空间缩进一起使用...

任何改进将受到欢迎!

最佳答案

您可以将字符串包装到下一行以获得所需的缩进:

    string div =
@"
<div class=""className"">
    <span>Mon text</span>
</div>"
.TrimStart(); // to remove the additional new-line at the beginning


另一个不错的解决方案(缺点:取决于缩进级别!)

        string div = @"
        <div class=""className"">
        <span>Mon text</span>
        </div>".TrimStart().Replace("\n            ", "\n");


它只是从字符串中删除缩进。确保Replace的第一个字符串中的空格数与您的缩进相同。

关于c# - 作用于C#多行字符串的缩进,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38523090/

10-11 22:36
查看更多