【问题标题】:Adding Xelement into an existing Xelement in foreach loop在 foreach 循环中将 Xelement 添加到现有 Xelement
【发布时间】:2014-09-24 14:14:20
【问题描述】:

例如,如果我有一个包含两个对象的列表,并且我想使用 Xelement 将它们放入 XML 文件中,并尝试遍历对象,它会将第二个对象项放入第一个 Xelement 名称中,因为它们具有相同的 Xelement标签名称。

我如何告诉 Xelement 它需要在某种方面是唯一的?所以它不会将第二个对象放在第一个人物标签中,而是放在第二个标签中。

List<People> people -> has two items

foreach (var person in people)
{
 xmlDoc.Element("people").Add(new XElement("person"............

}

XML 输出示例:

<people>
     <person></person>
     <person></person>
</people>
<people>
</people>

【问题讨论】:

  • 在不评论“为什么”的情况下给它一个 -1 是没有帮助的。 ;) 我可以在这里发布整个代码。但我认为这已经很清楚了,因为它不是那么难的主题。

标签: c# .net xml xelement


【解决方案1】:

没关系,我已经找到答案了。

使用 Element 将为您提供他可以在您的 XML 文档中找到的第一个元素。

使用Elements("people").Last().Element("person").Add 会给你集合中的最后一个。当我循环遍历对象时,最后一个将永远是我在那一刻所处的那个。

还是谢谢。

【讨论】:

  • 谢谢,在 2016 年仍然有用 :)
【解决方案2】:

问题不是很清楚,但您可能正在寻找这样的东西?

    foreach (var p in people)
    {
        XElement xElement = new XElement("people");

        foreach (var person in p)
        {
            xElement.Add(new XElement("person")); // add other elements, attributes etc...,
        }

        xDoc.Add(xElement);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多