【问题标题】:XDocument/Linq concatenate attribute values as comma separated listXDocument/Linq 将属性值连接为逗号分隔列表
【发布时间】:2025-12-12 14:35:01
【问题描述】:

如果我有以下 xml:

        XDocument xDocument = new XDocument(
            new XElement("RootElement",
                new XElement("ChildElement",
                    new XAttribute("Attribute1", "Hello"),
                    new XAttribute("Attribute2", "World")
                ),
                new XElement("ChildElement",
                    new XAttribute("Attribute1", "Foo"),
                    new XAttribute("Attribute2", "Bar")
                )
            )
        );

我正在使用 LINQ “。”输出“Hello,Foo”。符号。

我可以使用

得到“你好”
xDocument.Element("RootElement").Element("ChildElement").Attribute("Attribute1").Value;

我可以使用所有的属性

xDocument.Element("RootElement").Elements("ChildElement").Attributes("Attribute1");

如何获取属性的字符串值列表,以便我可以将其作为逗号分隔列表加入?

【问题讨论】:

    标签: c# linq concatenation linq-to-xml


    【解决方案1】:
    var strings = from attribute in 
                           xDocument.Descendants("ChildElement").Attributes()
                  select attribute.Value;
    

    【讨论】:

    • 我需要使用 .表示法而不是使用 linq 查询。但是,+1 因为你完全指出了我正确的方向。
    • 啊抱歉,我通常使用查询语法只是出于习惯。
    【解决方案2】:

    好的,感谢 womp,我意识到这是获取属性 Value 所需的 Select 方法,因此我可以获得字符串数组。因此,以下工作。

    String.Join(",", (string[]) xDocument.Element("RootElement").Elements("ChildElement").Attributes("Attribute1").Select(attribute => attribute.Value).ToArray());
    

    【讨论】:

      最近更新 更多