Evaluar y enviar comentarios

  Encender vista de ancho de banda bajo
Esta página es específica de
Microsoft Visual Studio 2008/.NET Framework 3.5

Hay además otras versiones disponibles para:
Biblioteca de clases de .NET Framework
XContainer..::.Element (Método)

Actualización: noviembre 2007

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)
Visual Basic (Declaración)
Public Function Element ( _
    name As XName _
) As XElement
Visual Basic (Uso)
Dim instance As XContainer
Dim name As XName
Dim returnValue As XElement

returnValue = instance.Element(name)
C#
public XElement Element(
    XName name
)
Visual C++
public:
XElement^ Element(
    XName^ name
)
J#
public XElement Element(
    XName name
)
JScript
public function 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 nullNothingnullptrreferencia null (Nothing en Visual Basic).

Devuelve nullNothingnullptrreferencia null (Nothing en Visual Basic) 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 nullNothingnullptrreferencia null (Nothing en Visual Basic) 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 nullNothingnullptrreferencia null (Nothing en Visual Basic) 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.

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:

<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:

<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>

Windows Vista, Windows XP SP2, Windows Server 2003, Windows CE, Windows Mobile para Smartphone, Windows Mobile para Pocket PC

.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

.NET Framework

Compatible con: 3.5

.NET Compact Framework

Compatible con: 3.5
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2009 Microsoft Corporation. Reservados todos los derechos. Términos de uso  |  Marcas Registradas  |  Privacidad
Page view tracker