4

如果我有以下 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");

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

4

2 回答 2

2
var strings = from attribute in 
                       xDocument.Descendants("ChildElement").Attributes()
              select attribute.Value;
于 2009-09-02T16:15:22.000 回答
2

好的,多亏了 womp,我意识到这是我需要的 Select 方法来获取属性 Value ,这样我就可以获得一个字符串数组。因此,以下工作。

String.Join(",", (string[]) xDocument.Element("RootElement").Elements("ChildElement").Attributes("Attribute1").Select(attribute => attribute.Value).ToArray());
于 2009-09-02T16:46:09.877 回答