如何将此StringBuilder-to-XML代码更改为LINQ-to-XML?

时间:2009-06-23 12:40:44

标签: c# linq stringbuilder

在我的应用程序中,我使用 StringBuilder 构建了一个包含此代码的XML文件:

StringBuilder sb = new StringBuilder();
sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine);

sb.Append(String.Format("<{0}>{1}", _pluralCamelNotation, Environment.NewLine));
for (int index = 0; index < 3; index++)
{
    sb.Append(String.Format("\t<{0}>{1}", _singularCamelNotation, Environment.NewLine));
    foreach (DataType dataType in _allDataTypes)
    {
        sb.Append(String.Format("\t\t<{0}>{2}</{0}>{1}", dataType.CamelCaseNotation, Environment.NewLine, dataType.GetDummyData()));
    }
    sb.Append(String.Format("\t</{0}>{1}", _singularCamelNotation, Environment.NewLine));
}
sb.Append(String.Format("</{0}>{1}", _pluralCamelNotation, Environment.NewLine));

return sb.ToString();

如何使用 LINQ 执行相同的操作,如下所示:

PSEUDO-CODE:

var xdoc = new XDocument(
    new XDeclaration("1.0", "utf-8", null),
    for (int index = 0; index < 3; index++) {
        new XElement(_pluralCamelNotation,
            _allDataTypes.Select(datatype => new XElement(_singularCamelNotation,
                new XElement(datatype.CamelCaseNotation, datatype.GetDummyData())
            ))
        )
    }
);

3 个答案:

答案 0 :(得分:11)

即使没有LINQ,也不应该通过连接编写xml ... XmlWriter将是一个不错的选择:

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.NewLineHandling = NewLineHandling.Entitize;
    settings.Indent = true;
    settings.IndentChars = "\t";

    StringBuilder sb = new StringBuilder();
    using (XmlWriter xw = XmlWriter.Create(sb, settings))
    {
        xw.WriteStartDocument();
        xw.WriteStartElement(_pluralCamelNotation);
        for (int i = 0; i < 3; i++)
        {
            xw.WriteStartElement(_singularCamelNotation);
            foreach (DataType dataType in _allDataTypes)
            {
                xw.WriteElementString(dataType.ToString(),
                    dataType.GetDummyData());
            }
            xw.WriteEndElement();
        }
        xw.WriteEndElement();
        xw.WriteEndDocument();
        xw.Close();
    }

您可以使用XmlWriterSettings来控制行间距等内容。

或者,使用LINQ-to-XML:

    XDocument doc = new XDocument(
        new XDeclaration("1.0", null, null),
        new XElement(_pluralCamelNotation, 
            Enumerable.Range(1,3).Select(
                i => new XElement(_singularCamelNotation,
                    _allDataTypes.Select(
                        dataType => new XElement(
                            dataType.ToString(),
                            dataType.GetDummyData())
                    )
            ))));

    string t = doc.ToString();

答案 1 :(得分:2)

这是VB.Net利用XML文字赢得C#的一个领域。请查看从http://blogs.msdn.com/jimoneil/archive/2009/06/15/x-is-for-xml-literal.aspx获取的代码。那不是很漂亮吗?

Dim xml = <?xml version="1.0"?>
      <menu>
          <course name="appetizer">
              <%= From m In menu _
                  Where m.Course = "appetizer" _
                  Select <dish><%= m.Food %></dish> _
              %>
          </course>
          <course name="main">
              <%= From m In menu _
                  Where m.Course = "main" _
                  Select <dish><%= m.Food %></dish> _
              %>
          </course>
          <course name="dessert">
              <%= From m In menu _
                  Where m.Course = "dessert" _
                  Select <dish><%= m.Food %></dish> _
              %>
          </course>
      </menu>

答案 2 :(得分:0)

如果你的意思是这一行:

_allDataTypes.Select(datatype => new XElement(_singularCamelNotation,
                new XElement(datatype.CamelCaseNotation, datatype.GetDummyData())
            ))

和_allDataTypes是一个List(注意不是LinQ!)你可以这样做:

_allDataTypes.ForEach(datatype => new XElement(_singularCamelNotation,
                new XElement(datatype.CamelCaseNotation, datatype.GetDummyData())
            ))

请注意,这只适用于List。