C# XDocument/Linq将属性值连接为逗号分隔列表
如果我有以下xml:C# XDocument/Linq将属性值连接为逗号分隔列表,c#,linq,concatenation,linq-to-xml,C#,Linq,Concatenation,Linq To Xml,如果我有以下xml: XDocument xDocument = new XDocument( new XElement("RootElement", new XElement("ChildElement", new XAttribute("Attribute1", "Hello"), new XAttribute("Attribute2", "
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").Elements("ChildElement").Attributes("Attribute1");
如何获取属性的字符串值列表,以便将其作为逗号分隔的列表连接起来?好的,多亏了womp,我意识到这是获取属性值所需的Select方法,以便获取字符串数组。因此,下面的工作
var strings = from attribute in
xDocument.Descendants("ChildElement").Attributes()
select attribute.Value;
String.Join(",", (string[]) xDocument.Element("RootElement").Elements("ChildElement").Attributes("Attribute1").Select(attribute => attribute.Value).ToArray());
我需要用电脑来做。表示法,而不是使用linq查询。但是,+1,因为你给我指出了正确的方向。啊,对不起,我通常只是出于习惯而使用查询语法。
String.Join(",", (string[]) xDocument.Element("RootElement").Elements("ChildElement").Attributes("Attribute1").Select(attribute => attribute.Value).ToArray());