Compartir a través de


Recuperación de nodo desordenado por nombre o índice

XmlNamedNodeMap se describe en la especificación World Wide Web Consortium (W3C) como NamedNodeMap y es necesario para controlar un conjunto desordenado de nodos con la capacidad de hacer referencia a los nodos por su nombre o índice. La única forma en que tiene acceso a un XmlNamedNodeMap es cuando un XmlNamedNodeMap se devuelve a través de un método o propiedad. Hay tres métodos o propiedades que devuelven un XmlNamedNodeMap:

  • XmlElement.Atributos

  • XmlDocumentType.Entities

  • XmlDocumentType.Notations

Por ejemplo, la propiedad XmlDocumentType.Entities obtiene la colección de nodos XmlEntity declarados en la declaración de tipo de documento. Esta colección se devuelve como XmlNamedNodeMap y se puede recorrer en iteración la colección con el uso de la propiedad Count y mostrar información de entidad. Para obtener un ejemplo de iteración a través de xmlNamedNodeMap, vea Entities.

XmlAttributeCollection se deriva de XmlNamedNodeMap y solo se pueden modificar los atributos, mientras que las notaciones y las entidades son de solo lectura. Con XmlNamedNodeMap para los atributos, puede obtener nodos para esos atributos en función de sus nombres XML. Esto proporciona un método sencillo para manipular la colección de atributos en un nodo de elemento. Esto se puede comparar directamente con XmlNodeList, que también implementa la interfaz IEnumerable , pero con un descriptor de acceso de índice en lugar de una cadena. Los métodos RemoveNamedItem y SetNamedItem solo se usan en xmlAttributeCollection. Agregar o quitar de una colección de atributos, ya sea mediante la implementación AttributeCollection o XmlNamedNodeMap , modifica la colección de atributos en el elemento . En el ejemplo de código siguiente se muestra cómo mover un atributo y crear un nuevo atributo.

Imports System  
Imports System.Xml  
  
Class test  
  
    Public Shared Sub Main()  
        Dim doc As New XmlDocument()  
        doc.LoadXml("<root> <child1 attr1='val1' attr2='val2'> text1 </child1> <child2 attr3='val3'> text2 </child2> </root> ")  
  
        ' Get the attributes of node "child2 "  
        Dim ac As XmlAttributeCollection = doc.DocumentElement.ChildNodes(1).Attributes  
  
        ' Print out the number of attributes and their names.  
        Console.WriteLine(("Number of Attributes: " + ac.Count))  
        Dim i As Integer  
        For i = 0 To ac.Count - 1  
            Console.WriteLine((i + 1 + ".  Attribute Name: '" + ac(i).Name + "'  Attribute Value:  '" + ac(i).Value + "'"))  
        Next i  
        ' Get the 'attr1' from child1.  
        Dim attr As XmlAttribute = doc.DocumentElement.ChildNodes(0).Attributes(0)  
  
        ' Add this attribute to the attributecollection "ac".  
        ac.SetNamedItem(attr)  
  
        ''attr1' will be removed from 'child1' and added to 'child2'.  
        ' Print out the number of attributes and their names.  
        Console.WriteLine(("Number of Attributes: " + ac.Count))  
  
        For i = 0 To ac.Count - 1  
            Console.WriteLine((i + 1 + ".  Attribute Name: '" + ac(i).Name + "'  Attribute Value:  '" + ac(i).Value + "'"))  
        Next i  
        ' Create a new attribute and add to the collection.  
        Dim attr2 As XmlAttribute = doc.CreateAttribute("attr4")  
        attr2.Value = "val4"  
        ac.SetNamedItem(attr2)  
  
        ' Print out the number of attributes and their names.  
        Console.WriteLine(("Number of Attributes: " + ac.Count))  
  
        For i = 0 To ac.Count - 1  
            Console.WriteLine((i + 1 + ".  Attribute Name: '" + ac(i).Name + "'  Attribute Value:  '" + ac(i).Value + "'"))  
        Next i  
    End Sub 'Main  
End Class 'test  
using System;  
using System.Xml;  
class test {  
    public static void Main() {  
        XmlDocument doc = new XmlDocument();  
        doc.LoadXml( "<root> <child1 attr1='val1' attr2='val2'> text1 </child1> <child2 attr3='val3'> text2 </child2> </root> " );  
  
        // Get the attributes of node "child2"  
        XmlAttributeCollection ac = doc.DocumentElement.ChildNodes[1].Attributes;  
  
        // Print out the number of attributes and their names.  
        Console.WriteLine( "Number of Attributes: "+ac.Count );  
        for( int i = 0; i < ac.Count; i++ )  
            Console.WriteLine( (i+1) + ".  Attribute Name: '" +ac[i].Name+ "'  Attribute Value:  '"+ ac[i].Value +"'" );
  
        // Get the 'attr1' from child1.  
        XmlAttribute attr = doc.DocumentElement.ChildNodes[0].Attributes[0];  
  
        // Add this attribute to the attributecollection "ac".  
        ac.SetNamedItem( attr );  
  
        // 'attr1' will be removed from 'child1' and added to 'child2'.  
        // Print out the number of attributes and their names.  
        Console.WriteLine( "Number of Attributes: "+ac.Count );
        for( int i = 0; i < ac.Count; i++ )  
            Console.WriteLine( (i+1) + ".  Attribute Name: '" +ac[i].Name+ "'  Attribute Value:  '"+ ac[i].Value +"'" );
  
        // Create a new attribute and add to the collection.  
        XmlAttribute attr2 = doc.CreateAttribute( "attr4" );  
        attr2.Value = "val4";  
        ac.SetNamedItem( attr2 );  
  
        // Print out the number of attributes and their names.  
        Console.WriteLine( "Number of Attributes: "+ac.Count );
        for( int i = 0; i < ac.Count; i++ )  
            Console.WriteLine( (i+1) + ".  Attribute Name: '" +ac[i].Name+ "'  Attribute Value:  '"+ ac[i].Value +"'" );
  
    }  
}  

Para ver un ejemplo de código adicional que muestra un atributo que se quita de attributeCollection, vea XmlNamedNodeMap.RemoveNamedItem (método). Para más información sobre los métodos y las propiedades, vea XmlNamedNodeMap (miembros).

Consulte también