使用linq聚合函数构建xml字符串?

发布于 2024-08-09 12:58:46 字数 406 浏览 9 评论 0原文

我过去用它来构建逗号分隔的列表:

var list = new List<int>{1,2,3};
var retVal = list.Select(i=>i.ToString()).Aggregate((a,b) => a+", "+b);

效果很好。

我正在尝试做同样的事情来将每个元素“包装”为 xml 节点。

类似的东西:

Aggregate((a, b) => string.Format("<ID>{0}</ID><ID>{1}</ID>", a,b))

不过似乎不太能使其发挥作用。是否可以?或者有更简单的方法吗?

谢谢。

I've used this in the past to build comma seperated lists:

var list = new List<int>{1,2,3};
var retVal = list.Select(i=>i.ToString()).Aggregate((a,b) => a+", "+b);

Works great.

I'm trying to do the same sort of thing to 'wrap' each element as an xml node.

Something like:

Aggregate((a, b) => string.Format("<ID>{0}</ID><ID>{1}</ID>", a,b))

Can't quite seem to make it work though. Is it possible? Or is there an easier way entirely?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

述情 2024-08-16 12:58:46

Blindy 的答案肯定会起作用,但我个人会使用:

var list = new List<int> {1, 2, 3};
var joined = string.Join("", list.Select(x => "<ID>" + x + "</ID>")
                                 .ToArray());

我个人发现这比聚合更容易阅读和理解。我相信它也会更高效——尽管这只对大型列表很重要。

Blindy's answer will certainly work, but I'd personally use:

var list = new List<int> {1, 2, 3};
var joined = string.Join("", list.Select(x => "<ID>" + x + "</ID>")
                                 .ToArray());

I personally find that easier to read and understand than the aggregation. I believe it will be more efficient, too - although that will only matter for large lists.

茶花眉 2024-08-16 12:58:46

或者有更简单的方法吗?

List<int> list = new List<int>{1, 2, 3};
var xmlNodes = list.Select(i => new XElement("ID", i));
XElement xml = new XElement("Data", xmlNodes);
Console.WriteLine(xml);

Or is there an easier way entirely?

List<int> list = new List<int>{1, 2, 3};
var xmlNodes = list.Select(i => new XElement("ID", i));
XElement xml = new XElement("Data", xmlNodes);
Console.WriteLine(xml);
吖咩 2024-08-16 12:58:46

难道不应该是这样的:

Aggregate((a, b) => string.Format("{0}<ID>{1}</ID>", a,b))

您正在添加一个新节点。

Shouldn't it be like:

Aggregate((a, b) => string.Format("{0}<ID>{1}</ID>", a,b))

You're adding to a new nodes.

你又不是我 2024-08-16 12:58:46

有很多方法可以实现这一目标,但我怀疑正确的答案是“视情况而定”。创建 CSV 字符串的原始示例使用字符串连接运算符;推荐的方法是使用 StringBuilder 类来实现此目的。在 .Net 4.0 中,string.Join() 方法有一个新的重载,该方法更易于使用和理解。

// .Net 3.5
var list = new List<int>{1,2,3};
var csv = list.Aggregate(new StringBuilder(), 
    (sb, i) => sb.Append(i).Append(','),
    sb => { if (sb.Length > 0) sb.Length--; return sb.ToString(); });

// .Net 4.0
var csv1 = string.Join(",", list);

如果您的目的是创建 XML 文档而不是字符串,则 David B 上面的答案是一个不错的选择:

var xml = new XElement("Root", list.Select(i => new XElement("ID", i)));
// <Root>
//   <ID>1</ID>
//   <ID>2</ID>
//   <ID>3</ID>
// </Root> 

对于创建 XML 字符串,我更喜欢避免显式编码开始和结束标记。在您的示例中,很难在开始或结束标记中使元素名称“ID”不正确,但我根据 DRY 原则来考虑这一点。有时,当我修改了配置文件中的开始标签时,我忘记修改元素的结束标签。使用XElement完全避免了这个问题:

// .Net 3.5
var xml1 = list.Aggregate(new StringBuilder(), 
           (sb, i) => sb.Append(new XElement("ID", i)),
           sb => sb.ToString());

// .Net 4.0
var xml2 = string.Join("", list.Select (i => new XElement("ID", i)));
// both xml1 & xml2 contain "<ID>1</ID><ID>2</ID><ID>3</ID>"

Aggregate()string.Join()string.Join()的性能对比em> 每次都会获胜(使用我使用的相当有限/基本的测试用例)。

There are a number of ways to achieve this but I suspect the correct answer is "it depends". Your original example for creating a CSV string uses the string concatenation operator; the recommended approach is to use the StringBuilder class for this purpose. And in .Net 4.0 there is a new overload for the string.Join() method that is a whole lot simpler to use and understand.

// .Net 3.5
var list = new List<int>{1,2,3};
var csv = list.Aggregate(new StringBuilder(), 
    (sb, i) => sb.Append(i).Append(','),
    sb => { if (sb.Length > 0) sb.Length--; return sb.ToString(); });

// .Net 4.0
var csv1 = string.Join(",", list);

If your intention is to create an XML Document rather than a string then David B's answer above is a good option:

var xml = new XElement("Root", list.Select(i => new XElement("ID", i)));
// <Root>
//   <ID>1</ID>
//   <ID>2</ID>
//   <ID>3</ID>
// </Root> 

For creating XML strings I prefer to avoid explicitly coding opening and closing tags. In your example it would be difficult to get the element name "ID" incorrect in either opening or closing tags but I think of this in terms of the DRY principle. On occasion I have forgotten to modify the closing tag for an element when I have modified the opening tag e.g. in config files. Using XElement avoids this issue completely:

// .Net 3.5
var xml1 = list.Aggregate(new StringBuilder(), 
           (sb, i) => sb.Append(new XElement("ID", i)),
           sb => sb.ToString());

// .Net 4.0
var xml2 = string.Join("", list.Select (i => new XElement("ID", i)));
// both xml1 & xml2 contain "<ID>1</ID><ID>2</ID><ID>3</ID>"

Performance of Aggregate() versus string.Join(), string.Join() wins every time (with the fairly limited/basic test case I used).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文