gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:04:14 25 4
gpt4 key购买 nike

在我的应用程序中,我使用 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())
))
)
}
);

最佳答案

即使没有 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();

关于c# - 如何将此 StringBuilder-to-XML 代码更改为 LINQ-to-XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1032314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com