Extensions.Attributes Метод

Определение

Возвращает коллекцию атрибутов каждого элемента в исходной коллекции.

Перегрузки

Имя Описание
Attributes(IEnumerable<XElement>)

Возвращает коллекцию атрибутов каждого элемента в исходной коллекции.

Attributes(IEnumerable<XElement>, XName)

Возвращает отфильтрованную коллекцию атрибутов каждого элемента в исходной коллекции. В коллекцию включены только элементы с соответствующими XName.

Комментарии

Visual Basic пользователи могут использовать ось интегрированных атрибутов для получения атрибутов с определенным именем из коллекции элементов.

Этот метод использует отложенное выполнение.

Attributes(IEnumerable<XElement>)

Исходный код:
Extensions.cs
Исходный код:
Extensions.cs
Исходный код:
Extensions.cs
Исходный код:
Extensions.cs
Исходный код:
Extensions.cs

Возвращает коллекцию атрибутов каждого элемента в исходной коллекции.

public:
[System::Runtime::CompilerServices::Extension]
 static System::Collections::Generic::IEnumerable<System::Xml::Linq::XAttribute ^> ^ Attributes(System::Collections::Generic::IEnumerable<System::Xml::Linq::XElement ^> ^ source);
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source);
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement?> source);
static member Attributes : seq<System.Xml.Linq.XElement> -> seq<System.Xml.Linq.XAttribute>
<Extension()>
Public Function Attributes (source As IEnumerable(Of XElement)) As IEnumerable(Of XAttribute)

Параметры

source
IEnumerable<XElement>

IEnumerable<T> ОбъектXElement, содержащий исходную коллекцию.

Возвращаемое значение

IEnumerable<T> Содержит XAttribute атрибуты каждого элемента в исходной коллекции.

Примеры

В следующем примере извлекается коллекция элементов, а затем извлекается коллекция всех атрибутов всех элементов в коллекции. Обратите внимание, что результирующая коллекция включает только атрибуты Child1 и Child2 элементы, а не атрибуты Root элемента.

Обратите внимание, что атрибут пространства имен возвращается этим методом.

XElement xmlTree = new XElement("Root",
    new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"),
    new XAttribute("Att1", "content1"),
    new XAttribute("Att2", "content2"),
    new XElement("Child1",
        new XAttribute("Att1", "content3"),
        new XAttribute("Att2", "content4")
    ),
    new XElement("Child2",
        new XAttribute("Att1", "content5"),
        new XAttribute("Att2", "content6")
    )
);
Console.WriteLine(xmlTree);
Console.WriteLine("-----");

IEnumerable<XAttribute> attList =
    from att in xmlTree.DescendantsAndSelf().Attributes()
    select att;

foreach (XAttribute att in attList)
    Console.WriteLine(att);
Dim xmlTree As XElement = _
    <Root xmlns:aw="http://www.adventure-works.com" Att1="content1" Att2="content2">
        <Child1 Att1="content3" Att2="content4"/>
        <Child2 Att1="content5" Att2="content6"/>
    </Root>

Dim attList = _
    From att In xmlTree.DescendantsAndSelf.Attributes _
    Select att

Console.WriteLine(xmlTree)
Console.WriteLine("-----")

For Each att As XAttribute In attList
    Console.WriteLine(att)
Next

В примере получается следующий вывод.

<Root xmlns:aw="http://www.adventure-works.com" Att1="content1" Att2="content2">
  <Child1 Att1="content3" Att2="content4" />
  <Child2 Att1="content5" Att2="content6" />
</Root>
-----
xmlns:aw="http://www.adventure-works.com"
Att1="content1"
Att2="content2"
Att1="content3"
Att2="content4"
Att1="content5"
Att2="content6"

Ниже приведен тот же пример, но в этом случае XML находится в пространстве имен. Дополнительные сведения см. в статье "Работа с пространствами имен XML". Обратите внимание, что атрибут пространства имен включен в возвращаемую коллекцию.

XNamespace aw = "http://www.adventure-works.com";
XElement xmlTree = new XElement(aw + "Root",
    new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"),
    new XAttribute(aw + "Att1", "content1"),
    new XAttribute(aw + "Att2", "content2"),
    new XElement(aw + "Child1",
        new XAttribute(aw + "Att1", "content3"),
        new XAttribute(aw + "Att2", "content4")
    ),
    new XElement(aw + "Child2",
        new XAttribute(aw + "Att1", "content5"),
        new XAttribute(aw + "Att2", "content6")
    )
);
Console.WriteLine(xmlTree);
Console.WriteLine("-----");

IEnumerable<XAttribute> attList =
    from att in xmlTree.DescendantsAndSelf().Attributes()
    select att;

foreach (XAttribute att in attList)
    Console.WriteLine(att);
Imports <xmlns:aw="http://www.adventure-works.com">

Module Module1
    Sub Main()
        Dim xmlTree As XElement = _
            <aw:Root xmlns:aw="http://www.adventure-works.com" aw:Att1="content1" aw:Att2="content2">
                <aw:Child1 aw:Att1="content3" aw:Att2="content4"/>
                <aw:Child2 aw:Att1="content5" aw:Att2="content6"/>
            </aw:Root>

        Dim attList = _
            From att In xmlTree.DescendantsAndSelf.Attributes _
            Select att

        Console.WriteLine(xmlTree)
        Console.WriteLine("-----")

        For Each att As XAttribute In attList
            Console.WriteLine(att)
        Next
    End Sub
End Module

В примере получается следующий вывод.

<aw:Root xmlns:aw="http://www.adventure-works.com" aw:Att1="content1" aw:Att2="content2">
  <aw:Child1 aw:Att1="content3" aw:Att2="content4" />
  <aw:Child2 aw:Att1="content5" aw:Att2="content6" />
</aw:Root>
-----
xmlns:aw="http://www.adventure-works.com"
aw:Att1="content1"
aw:Att2="content2"
aw:Att1="content3"
aw:Att2="content4"
aw:Att1="content5"
aw:Att2="content6"

Комментарии

Обратите внимание, что в отличие от некоторых других интерфейсов программирования XML в LINQ to XML пространства имен отображаются как атрибуты.

Хотя Visual Basic пользователи могут использовать ось интегрированных атрибутов для получения атрибутов с указанным именем из коллекции элементов, для получения всех атрибутов в коллекции нет интегрированной оси Visual Basic.

Этот метод использует отложенное выполнение.

См. также раздел

Применяется к

Attributes(IEnumerable<XElement>, XName)

Исходный код:
Extensions.cs
Исходный код:
Extensions.cs
Исходный код:
Extensions.cs
Исходный код:
Extensions.cs
Исходный код:
Extensions.cs

Возвращает отфильтрованную коллекцию атрибутов каждого элемента в исходной коллекции. В коллекцию включены только элементы с соответствующими XName.

public:
[System::Runtime::CompilerServices::Extension]
 static System::Collections::Generic::IEnumerable<System::Xml::Linq::XAttribute ^> ^ Attributes(System::Collections::Generic::IEnumerable<System::Xml::Linq::XElement ^> ^ source, System::Xml::Linq::XName ^ name);
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> source, System.Xml.Linq.XName name);
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XAttribute> Attributes(this System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement?> source, System.Xml.Linq.XName? name);
static member Attributes : seq<System.Xml.Linq.XElement> * System.Xml.Linq.XName -> seq<System.Xml.Linq.XAttribute>
<Extension()>
Public Function Attributes (source As IEnumerable(Of XElement), name As XName) As IEnumerable(Of XAttribute)

Параметры

source
IEnumerable<XElement>

IEnumerable<T> ОбъектXElement, содержащий исходную коллекцию.

name
XName

Совпадение XName .

Возвращаемое значение

IEnumerable<T> Содержит XAttribute отфильтрованную коллекцию атрибутов каждого элемента в исходной коллекции. В коллекцию включены только элементы с соответствующими XName.

Примеры

В следующем примере извлекается коллекция элементов, которые в данном случае включают в себя Child1 и Child2 элементы. Затем он извлекает все атрибуты этой дочерней коллекции с именем Att1.

XElement xmlTree = new XElement("Root",
    new XAttribute("Att1", "content1"),
    new XAttribute("Att2", "content2"),
    new XElement("Child1",
        new XAttribute("Att1", "content3"),
        new XAttribute("Att2", "content4")
    ),
    new XElement("Child2",
        new XAttribute("Att1", "content5"),
        new XAttribute("Att2", "content6")
    )
);

IEnumerable<XAttribute> attList = from att in xmlTree.Elements().Attributes("Att1")
                                  select att;

foreach (XAttribute att in attList)
    Console.WriteLine(att);
Dim xmlTree As XElement = _
    <Root Att1="content1" Att2="content2">
        <Child1 Att1="content3" Att2="content4">
        </Child1>
        <Child2 Att1="content5" Att2="content6">
        </Child2>
    </Root>

Dim attList = From att In xmlTree.Elements.Attributes("Att1") _
                          Select att

For Each att As XAttribute In attList
    Console.WriteLine(att)
Next

В примере получается следующий вывод.

Att1="content3"
Att1="content5"

Комментарии

Обратите внимание, что в отличие от некоторых других интерфейсов программирования XML в LINQ to XML пространства имен отображаются как атрибуты.

Этот метод использует отложенное выполнение.

См. также раздел

Применяется к