Extensions.DescendantNodes<T>(IEnumerable<T>) Метод

Определение

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

C#
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodes<T> (this System.Collections.Generic.IEnumerable<T> source) where T : System.Xml.Linq.XContainer;
C#
public static System.Collections.Generic.IEnumerable<System.Xml.Linq.XNode> DescendantNodes<T> (this System.Collections.Generic.IEnumerable<T?> source) where T : System.Xml.Linq.XContainer;

Параметры типа

T

Тип объектов в source, ограниченный узлом XContainer.

Параметры

source
IEnumerable<T>

Интерфейс IEnumerable<T> узла XContainer, содержащий исходную коллекцию.

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

IEnumerable<XNode>

IEnumerable<T> для XNode подчиненных узлов каждого документа и элемента в исходной коллекции.

Примеры

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

C#
XElement xmlTree = XElement.Parse(  
@"<Root>  
    <Child>aaa<GrandChild anAttribute='xyz'>Text</GrandChild>  
        <!--a comment-->  
        <?xml-stylesheet type='text/xsl' href='test.xsl'?>  
    </Child>  
    <Child>ccc<GrandChild>Text</GrandChild>ddd</Child>  
</Root>");  
IEnumerable<XNode> nodes =  
    from node in xmlTree.Elements("Child").DescendantNodes()  
    select node;  

foreach (XNode node in nodes)  
{  
    switch (node.NodeType)  
    {  
        case XmlNodeType.Element:  
            Console.WriteLine("Element: {0}", ((XElement)node).Name);  
            break;  
        case XmlNodeType.Text:  
            Console.WriteLine("Text: {0}", ((XText)node).Value);  
            break;  
        case XmlNodeType.Comment:  
            Console.WriteLine("Comment: {0}", ((XComment)node).Value);  
            break;  
        case XmlNodeType.ProcessingInstruction:  
            Console.WriteLine("PI: {0}", ((XProcessingInstruction)node).Data);  
            break;  
    }  
}  

В этом примере выводятся следующие данные:

Text: aaa  
Element: GrandChild  
Text: Text  
Comment: a comment  
PI: type='text/xsl' href='test.xsl'  
Text: ccc  
Element: GrandChild  
Text: Text  
Text: ddd  

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

C#
XNamespace aw = "http://www.adventure-works.com";  
XElement xmlTree = XElement.Parse(  
@"<Root xmlns='http://www.adventure-works.com'>  
    <Child>aaa<GrandChild anAttribute='xyz'>Text</GrandChild>  
        <!--a comment-->  
        <?xml-stylesheet type='text/xsl' href='test.xsl'?>  
    </Child>  
    <Child>ccc<GrandChild>Text</GrandChild>ddd</Child>  
</Root>");  
IEnumerable<XNode> nodes =  
    from node in xmlTree.Elements(aw + "Child").DescendantNodes()  
    select node;  

foreach (XNode node in nodes)  
{  
    switch (node.NodeType)  
    {  
        case XmlNodeType.Element:  
            Console.WriteLine("Element: {0}", ((XElement)node).Name);  
            break;  
        case XmlNodeType.Text:  
            Console.WriteLine("Text: {0}", ((XText)node).Value);  
            break;  
        case XmlNodeType.Comment:  
            Console.WriteLine("Comment: {0}", ((XComment)node).Value);  
            break;  
        case XmlNodeType.ProcessingInstruction:  
            Console.WriteLine("PI: {0}", ((XProcessingInstruction)node).Data);  
            break;  
    }  
}  

В этом примере выводятся следующие данные:

Text: aaa  
Element: {http://www.adventure-works.com}GrandChild  
Text: Text  
Comment: a comment  
PI: type='text/xsl' href='test.xsl'  
Text: ccc  
Element: {http://www.adventure-works.com}GrandChild  
Text: Text  
Text: ddd  

Комментарии

Этот метод расширения оси используется и XElement объектыXDocument. Оба этих типа являются производными от XContainerэтого метода, поэтому этот метод работает с той IEnumerable<T> , XContainer которая содержит исходную коллекцию.

Хотя Visual Basic имеет интегрированную ось XML для элементов-потомков, нет интегрированной оси для узлов-потомков, поэтому Visual Basic пользователи должны явно использовать этот метод оси.

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

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

Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

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