XContainer.Element (Método) (System.Xml.Linq)

Cambiar vista:
Sin script
Biblioteca de clases de .NET Framework
XContainer.Element (Método)
Este artículo se tradujo de forma manual. Para mostrar esta página y el contenido original en inglés al mismo tiempo, cambie a Lightweight según sus preferencias de visualización.

Obtiene el primer elemento secundario (clasificado por documento) con el XName especificado.

Espacio de nombres:  System.Xml.Linq
Ensamblado:  System.Xml.Linq (en System.Xml.Linq.dll)
Sintaxis

Visual Basic
Public Function Element ( _
	name As XName _
) As XElement
C#
public XElement Element(
	XName name
)
Visual C++
public:
XElement^ Element(
	XName^ name
)
F#
member Element : 
        name:XName -> XElement 

Parámetros

name
Tipo: System.Xml.Linq.XName
XName que se va a comparar.

Valor devuelto

Tipo: System.Xml.Linq.XElement
Objeto XElement que coincide con el XName especificado, o null.
Comentarios

Devuelve null si no hay ningún elemento con el nombre especificado.

Algunos métodos de eje devuelven colecciones de elementos o atributos. Este método devuelve sólo un elemento único.

Este método devuelve null si no se encuentra el elemento con el nombre especificado. Todos los métodos que le permiten construir los elementos (el constructor de XElement, Add, etc.) aceptan null como un argumento válido. Esto le permite utilizar una expresión adecuada: puede llamar a este método como parte de la construcción funcional y el elemento se agrega al árbol XML que se va a construir si y sólo si el elemento existe en el árbol de origen. Esta expresión se muestra en el siguiente ejemplo.

A diferencia de Elements, este método no es de eje. No utiliza la ejecución diferida; simplemente devuelve un elemento cuando se le llama.

Ejemplos

En el siguiente ejemplo se muestran dos usos de este método. En un caso, el método busca el elemento en srcTree. En el segundo caso, el método no busca el elemento en el árbol de origen, no se agrega ningún elemento a xmlTree y no se produce ninguna excepción.

Observe que el ejemplo de Visual Basic utiliza la propiedad de XML secundaria. También se permite utilizar el método Element directamente en Visual Basic.

C#
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);
Visual Basic
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)

Este ejemplo produce el siguiente resultado:

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

A continuación se muestra el mismo ejemplo, pero en este caso el XML está en un espacio de nombres. Para obtener más información, consulte Trabajar con espacios de nombres XML.

C#
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);
Visual Basic
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

Este ejemplo produce el siguiente resultado:

xmlLang
<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>
Información de versión

.NET Framework

Compatible con: 4, 3.5

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1
Plataformas

Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
Vea también

Referencia

Otros recursos