Примечание
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
XmlNamedNodeMap описывается в спецификации Консорциума Всемирной паутины (W3C) как Именованный набор узлов и требуется для обработки неупорядоченного набора узлов с возможностью ссылаться на узлы по их имени или индексу. Единственный способ получить доступ к XmlNamedNodeMap — это когда XmlNamedNodeMap возвращается через метод или свойство. Существует три метода или свойства, возвращающие XmlNamedNodeMap:
XmlElement.Attributes
XmlDocumentType.Entity
XmlDocumentType.Notations
Например, свойство XmlDocumentType.Entity получает коллекцию узлов XmlEntity , объявленных в объявлении типа документа. Эта коллекция возвращается как XmlNamedNodeMap, и вы можете выполнять итерацию по коллекции с использованием свойства Count и отображения сведений о сущностях. Пример итерации по XmlNamedNodeMap см. в разделе Entities.
XmlAttributeCollection является производным от XmlNamedNodeMap, а только атрибуты изменяются, а нотации и сущности доступны только для чтения. С помощью XmlNamedNodeMap для атрибутов можно получить узлы для этих атрибутов на основе их XML-имен. Это позволяет легко управлять коллекцией атрибутов на узле элемента. Можно сопоставить это напрямую с XmlNodeList, который также реализует интерфейс IEnumerable, но предоставляет доступ по индексу, а не по строке. Методы RemoveNamedItem и SetNamedItem используются только для XmlAttributeCollection. Добавление или удаление из коллекции атрибутов, независимо от того, используется ли атрибут AttributeCollection или реализация XmlNamedNodeMap , изменяет коллекцию атрибутов в элементе. В следующем примере кода показано, как переместить атрибут и создать новый атрибут.
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 +"'" );
}
}
Дополнительные примеры кода, показывающие удаление атрибута из AttributeCollection, см. в методе XmlNamedNodeMap.RemoveNamedItem. Дополнительные сведения о методах и свойствах см. в разделе "Элементы XmlNamedNodeMap".