Partilhar via


Recuperação de nó não ordenada por nome ou índice

O XmlNamedNodeMap é descrito na especificação do World Wide Web Consortium (W3C) como NamedNodeMap e é necessário para lidar com um conjunto não ordenado de nós com a capacidade de fazer referência a nós por seu nome ou índice. A única maneira de você ter acesso a um XmlNamedNodeMap é quando um XmlNamedNodeMap é retornado por meio de um método ou propriedade. Há três métodos ou propriedades que retornam um XmlNamedNodeMap:

  • XmlElement.Attributes

  • XmlDocumentType.Entities

  • XmlDocumentType.Notations

Por exemplo, a propriedade XmlDocumentType.Entities obtém a coleção de nós XmlEntity declarados na declaração de tipo de documento. Essa coleção é retornada como um XmlNamedNodeMap, e você pode iterar através da coleção com o uso da propriedade Count e exibir informações de entidade. Para obter um exemplo de iteração através de um XmlNamedNodeMap, consulte Entities.

O XmlAttributeCollection é derivado de XmlNamedNodeMap e apenas os atributos são modificáveis, enquanto notações e entidades são somente leitura. Usando o XmlNamedNodeMap para os atributos, você pode obter nós para esses atributos com base em seus nomes XML. Isso fornece um método fácil para manipular a coleção de atributos em um nó de elemento. Isso pode ser contrastado diretamente com XmlNodeList, que também implementa a interface IEnumerable , mas com um acessador de índice em vez de uma cadeia de caracteres. Os métodos RemoveNamedItem e SetNamedItem são usados apenas em um XmlAttributeCollection. Adicionar ou remover de uma coleção de atributos, seja usando o AttributeCollection ou a implementação XmlNamedNodeMap , modifica a coleção de atributos no elemento . O exemplo de código a seguir mostra como mover um atributo e criar um novo 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 um exemplo de código adicional que mostra um atributo sendo removido de um AttributeCollection, consulte Método XmlNamedNodeMap.RemoveNamedItem. Para obter mais informações sobre os métodos e propriedades, consulte Membros XmlNamedNodeMap.

Consulte também