XmlDocuments 在建立時,會特別針對該檔建立名稱數據表。 當 XML 載入檔中,或建立新的項目或屬性時,屬性和專案名稱會放入 XmlNameTable 中。 您也可以從另一份檔使用現有的 NameTable 來建立 XmlDocument。 使用採用 XmlNameTable 參數的建構函式建立 XmlDocuments 時,檔可以存取已儲存在 XmlNameTable 中的節點名稱、命名空間和前置詞。 無論名稱數據表如何載入名稱,一旦名稱儲存在數據表中,就可以使用對象比較快速比較名稱,而不是字串比較。 字串也可以使用Add新增至名稱表。 下列程式代碼範例顯示正在建立的名稱數據表,以及要新增至數據表的字串 MyString 。 之後,會使用該數據表建立 XmlDocument ,並將 Myfile.xml 中的專案和屬性名稱新增至現有的名稱數據表。
Dim nt As New NameTable()
nt.Add("MyString")
Dim doc As New XmlDocument(nt)
doc.Load("Myfile.xml")
NameTable nt = new NameTable();
nt.Add("MyString");
XmlDocument doc = new XmlDocument(nt);
doc.Load("Myfile.xml");
下列程式代碼範例示範如何建立檔、將兩個新元素新增至檔,這也會將它們新增至檔名稱數據表,以及名稱上的對象比較。
Dim doc1 As XmlDocument = imp.CreateDocument()
Dim node1 As XmlElement = doc.CreateElement("node1")
Dim doc2 As XmlDocument = imp.CreateDocument()
Dim node2 As XmlElement = doc.CreateElement("node2")
if (CType(node1.Name, object) = CType(node2.Name, object))
XmlDocument doc1 = imp.CreateDocument();
node1 = doc1.CreateElement ("node1");
XmlDocument doc2 = imp.CreateDocument();
node2 = doc2.CreateElement ("node1");
if (((object)node1.Name) == ((object)node2.Name))
{ ...
當重複處理相同類型的文件時,在兩份文件之間傳遞名稱表的情況是典型的,例如在電子商務網站上處理的訂單文件。這些文件符合 XML 架構定義語言(XSD)或文件類型定義(DTD),且同樣的字串會重複出現。 使用相同名稱數據表可提升效能,因為多個檔中發生相同的元素名稱。