XContainer.Element(XName) Метод

Определение

Возвращает первый дочерний элемент (в порядке документа) с указанным XNameэлементом.

public:
 System::Xml::Linq::XElement ^ Element(System::Xml::Linq::XName ^ name);
public System.Xml.Linq.XElement Element(System.Xml.Linq.XName name);
public System.Xml.Linq.XElement? Element(System.Xml.Linq.XName name);
member this.Element : System.Xml.Linq.XName -> System.Xml.Linq.XElement
Public Function Element (name As XName) As XElement

Параметры

name
XName

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

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

Значение XElement , соответствующее указанному XNameили null.

Примеры

В следующем примере показано два использования этого метода. В одном случае метод находит элемент в srcTree. Во втором случае метод не находит элемент в исходном дереве, ни один элемент не добавляется xmlTreeв, и исключение не возникает.

Обратите внимание, что в примере Visual Basic используется дочернее XML-свойство. Также можно использовать метод Element непосредственно в Visual Basic.

XElement srcTree = new XElement("Root",
    new XElement("Element1", 1),
    new XElement("Element2", 2),
    new XElement("Element3", 3),
    new XElement("Element4", 4),
    new XElement("Element5", 5)
);
XElement xmlTree = new XElement("Root",
    new XElement("Child1", 1),
    new XElement("Child2", 2),
    new XElement("Child3", 3),
    new XElement("Child4", 4),
    new XElement("Child5", 5),
    srcTree.Element("Element3"),
    // Even though Element9 does not exist in srcTree, the following line
    // will not throw an exception.
    srcTree.Element("Element9")
);
Console.WriteLine(xmlTree);
Dim srcTree As XElement = _
        <Root>
            <Element1>1</Element1>
            <Element2>2</Element2>
            <Element3>3</Element3>
            <Element4>4</Element4>
            <Element5>5</Element5>
        </Root>

Dim xmlTree As XElement = _
        <Root>
            <Child1>1</Child1>
            <Child2>2</Child2>
            <Child3>3</Child3>
            <Child4>4</Child4>
            <Child5>5</Child5>
            <%= srcTree.<Element3> %>
            <%= srcTree.<Element9> %>
        </Root>

' Even though Element9 does not exist in srcTree, adding it to the tree
' will not throw an exception.

Console.WriteLine(xmlTree)

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

<Root>
  <Child1>1</Child1>
  <Child2>2</Child2>
  <Child3>3</Child3>
  <Child4>4</Child4>
  <Child5>5</Child5>
  <Element3>3</Element3>
</Root>

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

XNamespace aw = "http://www.adventure-works.com";
XElement srcTree = new XElement(aw + "Root",
    new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"),
    new XElement(aw + "Element1", 1),
    new XElement(aw + "Element2", 2),
    new XElement(aw + "Element3", 3),
    new XElement(aw + "Element4", 4),
    new XElement(aw + "Element5", 5)
);
XElement xmlTree = new XElement(aw + "Root",
    new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"),
    new XElement(aw + "Child1", 1),
    new XElement(aw + "Child2", 2),
    new XElement(aw + "Child3", 3),
    new XElement(aw + "Child4", 4),
    new XElement(aw + "Child5", 5),
    srcTree.Element(aw + "Element3"),
    // Even though Element9 does not exist in srcTree, the following line
    // will not throw an exception.
    srcTree.Element(aw + "Element9")
);
Console.WriteLine(xmlTree);
Imports <xmlns:aw="http://www.adventure-works.com">

Module Module1
    Sub Main()
        Dim srcTree As XElement = _
            <aw:Root>
                <aw:Element1>1</aw:Element1>
                <aw:Element2>2</aw:Element2>
                <aw:Element3>3</aw:Element3>
                <aw:Element4>4</aw:Element4>
                <aw:Element5>5</aw:Element5>
            </aw:Root>

        Dim xmlTree As XElement = _
            <aw:Root>
                <aw:Child1>1</aw:Child1>
                <aw:Child2>2</aw:Child2>
                <aw:Child3>3</aw:Child3>
                <aw:Child4>4</aw:Child4>
                <aw:Child5>5</aw:Child5>
                <%= srcTree.<aw:Element3> %>
                <%= srcTree.<aw:Element9> %>
            </aw:Root>

        ' Even though Element9 does not exist in srcTree, adding it to the tree
        ' will not throw an exception.

        Console.WriteLine(xmlTree)
    End Sub
End Module

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

<aw:Root xmlns:aw="http://www.adventure-works.com">
  <aw:Child1>1</aw:Child1>
  <aw:Child2>2</aw:Child2>
  <aw:Child3>3</aw:Child3>
  <aw:Child4>4</aw:Child4>
  <aw:Child5>5</aw:Child5>
  <aw:Element3>3</aw:Element3>
</aw:Root>

Комментарии

Возвращает, null если нет элемента с указанным именем.

Некоторые методы оси возвращают коллекции элементов или атрибутов. Этот метод возвращает только один элемент.

Этот метод возвращает, null если элемент с указанным именем не найден. Все методы, позволяющие создавать элементы (конструктор XElement, Addи т. д.) принимать null в качестве допустимого аргумента. Это позволяет использовать удобный идиом: этот метод можно вызвать как часть функционального построения, и элемент добавляется в xml-дерево, создаваемое, если и только если элемент существует в исходном дереве. В следующем примере показана идиома.

В отличие от Elementsэтого метода, этот метод не является методом оси. Он не использует отложенное выполнение; он просто возвращает элемент при вызове.

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

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