System.Xml.XmlNamespaceManager Class

Assembly: System.Xml.dll
Namespace: System.Xml
Summary
Resolves, adds and removes namespaces to a collection and provide scope management for these namespaces. This class is used by the XsltContext and XmlReader classes.
C# Syntax:
public class XmlNamespaceManager : IEnumerable
Remarks
XmlNamespaceManager stores prefixes and namespaces as strings.
See also:
System.Xml Namespace

System.Xml.XmlNamespaceManager Member List:

Public Constructors
ctor #1 Initializes a new instance of the XmlNamespaceManager class with the specified XmlNameTable.
Public Properties
DefaultNamespace Read-only

Gets the namespace URI for the default namespace.
NameTable Read-only

Gets the XmlNameTable associated with this object.
Public Methods
AddNamespace Adds the given namespace to the collection.
Equals
(inherited from System.Object)
See base class member description: System.Object.Equals

Derived from System.Object, the primary base class for all objects.
GetEnumerator Provides support for the "foreach" style iteration over the collection of namespaces in the XmlNamespaceManager.
GetHashCode
(inherited from System.Object)
See base class member description: System.Object.GetHashCode

Derived from System.Object, the primary base class for all objects.
GetType
(inherited from System.Object)
See base class member description: System.Object.GetType

Derived from System.Object, the primary base class for all objects.
HasNamespace Gets a value indicating whether the supplied prefix has a namespace defined for the current pushed scope.
LookupNamespace Gets the namespace URI for the specified prefix.
LookupPrefix Finds the prefix declared for the given namespace URI.
PopScope Pops a namespace scope off the stack.
PushScope Pushes a namespace scope onto the stack.
RemoveNamespace Removes the given namespace for the given prefix.
ToString
(inherited from System.Object)
See base class member description: System.Object.ToString

Derived from System.Object, the primary base class for all objects.
Protected Methods
Finalize
(inherited from System.Object)
See base class member description: System.Object.Finalize

Derived from System.Object, the primary base class for all objects.
MemberwiseClone
(inherited from System.Object)
See base class member description: System.Object.MemberwiseClone

Derived from System.Object, the primary base class for all objects.

Hierarchy:


System.Xml.XmlNamespaceManager Member Details

ctor #1
Summary
Initializes a new instance of the XmlNamespaceManager class with the specified XmlNameTable.
C# Syntax:
public XmlNamespaceManager(
   XmlNameTable nameTable
);
Parameters:

nameTable

The XmlNameTable to use.

Exceptions
Exception Type Condition
NullReferenceException null is passed to the constructor
Remarks
The name table is used to look up prefixes and namespaces. An existing name table with pre-atomized strings can be specified in the constructor. There are several advantages in doing so. If a XmlReader's name table is used, after each read any namespace and prefix strings pushed into the name table can be re-used by XmlNamespaceManager. Also, because XmlNamespaceManager is used internally by the XmlReader, it can take advantage of the reader's ability to atomize strings.

For more information on atomized strings, see XmlNameTable.



Note If you specify an existing name table, any namespaces in the name table are not automatically added to XmlNamespaceManager. You must use XmlNamespaceManager.AddNamespace and XmlNamespaceManager.RemoveNamespace to add or remove namespaces.
Example
The following example creates an XmlNamespaceManager using the name table of the reader.
        XmlTextReader reader = new XmlTextReader("myfile.xml");
        XmlNamespaceManager nsmanager = new XmlNamespaceManager(reader.NameTable);
        nsmanager.AddNamespace("msbooks", "www.microsoft.com/books");
        nsmanager.PushScope();
        nsmanager.AddNamespace("msstore", "www.microsoft.com/store");
        while (reader.Read())
        {
            Console.WriteLine("Reader Prefix:{0}", reader.Prefix);
            Console.WriteLine("XmlNamespaceManager Prefix:{0}",
                              nsmanager.LookupPrefix(nsmanager.NameTable.Get(reader.NamespaceURI)));
        }

    

Return to top


Property: DefaultNamespace (read-only)
Summary
Gets the namespace URI for the default namespace.
C# Syntax:
public virtual string DefaultNamespace {get;}
Remarks
This method is equivalent to calling LookupNamespace(String.Empty).
Example
The following example displays the default namespace, if one exists.
if (nsmgr.HasNamespace(String.Empty))
  Console.WriteLine(nsmgr.DefaultNamespace);

    
See also:
XmlNamespaceManager.LookupNamespace

Return to top


Property: NameTable (read-only)
Summary
Gets the XmlNameTable associated with this object.
C# Syntax:
public XmlNameTable NameTable {get;}
Remarks
The name table is used to look up prefixes and namespace URIs.
See also:
XmlReader

Return to top


Method: AddNamespace(
   string prefix,
   string uri
)
Summary
Adds the given namespace to the collection.
C# Syntax:
public virtual void AddNamespace(
   string prefix,
   string uri
);
Parameters:

prefix

The prefix to associate with the namespace being added. Use String.Empty to add a default namespace.

uri

The namespace to add.

Exceptions
Exception Type Condition
InvalidOperationException The value for prefix is "xmlns".
Remarks
XmlNamespaceManager does not check prefix and uri for conformance.

XmlReader checks names, including prefixes and namespaces, to ensure they are valid XML names according to the W3C specification.XmlNamespaceManager is used internally by XmlReader, so to avoid a duplication of efforts, XmlNamespaceManager assumes all prefixes and namespaces are valid.

If the prefix and namespace already exists within the current scope, it will replace the existing prefix/namespace combination. The same prefix and namespace combination can exist across different scopes.

The following prefix/namespace pairs are added by default to the XmlNamespaceManager. They can be determined at any scope.



Prefix Namespace
xmlns http://www.w3.org/2000/xmlns/ (the xmlns prefix namespace)
xml http://www.w3.org/XML/1998/namespace (The XML namespace)
String.Empty String.Empty (The empty namespace). This value can be reassigned a different prefix. For example, xmlns="" defines the default namespace to be the empty namespace
Example
The following example uses XmlNamespaceManager to resolve namespaces in an XML fragment.
using System;
using System.IO;
using System.Xml;

//Reads an XML fragment

public class Sample
{
  public static void Main()
  {
    try
    {
      //The string containing the XML to read
      String xmlFrag="<book>" +
                     "<title>Pride And Prejudice</title>" +
                     "<author>" +
                     "<first-name>Jane</first-name>" +
                     "<last-name>Austen</last-name>" +
                     "</author>" +
                     "<curr:price>19.95</curr:price>" +
                     "<misc>&h;</misc>" +
                     "</book>";  

      ReadSample sample = new ReadSample(xmlFrag);
      sample.ReadIt();
            
    }
    catch (Exception e)
    {
      Console.WriteLine ("Exception: {0}", e.ToString());
    }

  }

} // End class

//Reads an XML fragment 

public class ReadSample
{
   XmlValidatingReader reader = null;
   
   public ReadSample(String xmlFrag)
   {

     //create an XmlNamespaceManager to resolve namespaces
     NameTable nt = new NameTable();
     XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
     nsmgr.AddNamespace(String.Empty, "urn:samples"); //default namespace
     nsmgr.AddNamespace("curr", "urn:samples:dollar");

     //Create an XmlParserContext.  The XmlParserContext contains all the information
     //required to parse the XML fragment, including the entity information
     XmlParserContext context;
     String subset="<!ENTITY h 'hardcover'>";
     context=new XmlParserContext(nt, nsmgr, "book", null, null, subset, null, null, XmlSpace.None);

     //create the reader
     reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);

   }

   //Read the XML fragment 
   public void ReadIt()
   {
    try
    {
      while(reader.Read())
      {
        if (reader.HasValue)
          Console.WriteLine("{0} [{1}] = {2}",reader.NodeType, reader.Name, reader.Value);
        else
          Console.WriteLine("{0} [{1}]",reader.NodeType, reader.Name);
      }

    }
    catch (Exception e)
    {
      Console.WriteLine ("Exception: {0}", e.ToString());
    }
   }
 
} //End class

    

Return to top


Method: Equals(
   object obj
)
Inherited
See base class member description: System.Object.Equals
C# Syntax:
public virtual bool Equals(
   object obj
);

For more information on members inherited from System.Object click on the link above.

Return to top


Method: Finalize()
Inherited
See base class member description: System.Object.Finalize
C# Syntax:
~XmlNamespaceManager();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetEnumerator()
Summary
Provides support for the "foreach" style iteration over the collection of namespaces in the XmlNamespaceManager.
C# Syntax:
public virtual IEnumerator GetEnumerator();
Return Value:
An IEnumerator.
Implements:
IEnumerable.GetEnumerator

Return to top


Method: GetHashCode()
Inherited
See base class member description: System.Object.GetHashCode
C# Syntax:
public virtual int GetHashCode();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: GetType()
Inherited
See base class member description: System.Object.GetType
C# Syntax:
public Type GetType();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: HasNamespace(
   string prefix
)
Summary
Gets a value indicating whether the supplied prefix has a namespace defined for the current pushed scope.
C# Syntax:
public virtual bool HasNamespace(
   string prefix
);
Parameters:

prefix

The prefix of the namespace you want to find.

Return Value:
true if there is a namespace defined; otherwise, false.
Remarks
To determine whether there is a default empty namespace defined, set prefix to String.Empty. If the method returns true, this indicates that there is a default namespace defined in current scope. Returning false indicates that no default namespace is defined.Note: xmlns:x= "" is illegal according to W3C Namespaces in XML recommendation.
Example
The following example displays the default namespace, if one it exists.
if (nsmgr.HasNamespace(String.Empty))
  Console.WriteLine(nsmgr.DefaultNamespace);

    

Return to top


Method: LookupNamespace(
   string prefix
)
Summary
Gets the namespace URI for the specified prefix.
C# Syntax:
public virtual string LookupNamespace(
   string prefix
);
Parameters:

prefix

The prefix whose namespace URI you want to resolve. To match the default namespace, pass String.Empty.

Return Value:
Returns the namespace URI for prefix or null if there is no mapped namespace. The returned string is atomized.

For more information on atomized strings, see XmlNameTable.

Example
The following example adds prefix/namespace pairs to the XmlNamespaceManager and then displays all the pairs in the collection.


using System;
using System.IO;
using System.Xml;


public class Sample
{
  public static void Main()
  {
    Sample test = new Sample();
  }
  public Sample()
  {
    //Create the XmlNamespaceManager.
    NameTable nt = new NameTable();
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);

    //Add prefix/namespace pairs to the XmlNamespaceManager.
    nsmgr.AddNamespace("", "www.wideworldimporters.com"); //Adds a default namespace.
    nsmgr.AddNamespace("europe", "www.wideworldimporters.com/europe");
    nsmgr.PushScope();  //Pushes a namespace scope on the stack.
    nsmgr.AddNamespace("", "www.lucernepublishing.com"); //Adds another default namespace.
    nsmgr.AddNamespace("partners", "www.lucernepublishing.com/partners");

    Console.WriteLine("Show all the prefix/namespace pairs in the XmlNamespaceManager...");
    ShowAllNamespaces(nsmgr);
  }

  private void ShowAllNamespaces(XmlNamespaceManager nsmgr)
  {
    do{
       foreach (String prefix in nsmgr)
       {
        Console.WriteLine("Prefix={0}, Namespace={1}", prefix,nsmgr.LookupNamespace(prefix));
       } 
    }
    while (nsmgr.PopScope());
  }
}

    

Return to top


Method: LookupPrefix(
   string uri
)
Summary
Finds the prefix declared for the given namespace URI.
C# Syntax:
public virtual string LookupPrefix(
   string uri
);
Parameters:

uri

The namespace to resolve for the prefix.

Return Value:
The matching prefix. If there is no mapped prefix, the method returns String.Empty. If a null value is supplied then null is returned.
Remarks
This method finds the mapped prefix by walking the stack (that is it looks globally). The supplied string must be atomized for the lookup to succeed. In other words the supplied string object must exist in the XmlNamespaceManager's XmlNamespaceManager.NameTable.

The returned string is also atomized. For more information on atomized strings, see XmlNameTable.

Example
The following example removes a namespace from the namespace manager.
String prefix = nsmgr.LookupPrefix("www.wideworldimporters.com/europe");
nsmgr.RemoveNamespace(prefix, "www.wideworldimporters.com/europe");

    

Return to top


Method: MemberwiseClone()
Inherited
See base class member description: System.Object.MemberwiseClone
C# Syntax:
protected object MemberwiseClone();

For more information on members inherited from System.Object click on the link above.

Return to top


Method: PopScope()
Summary
Pops a namespace scope off the stack.
C# Syntax:
public virtual bool PopScope();
Return Value:
true if there are namespace scopes left on the stack; false if there are no more namespaces to pop.
Remarks
When you call this method, all namespaces which were added to XmlNamespaceManager (by calling XmlNamespaceManager.AddNamespace) since the last call to PopScope, are removed.
Example
The following example adds prefix/namespace pairs to the XmlNamespaceManager and then displays all the pairs in the collection.


using System;
using System.IO;
using System.Xml;


public class Sample
{
  public static void Main()
  {
    Sample test = new Sample();
  }
  public Sample()
  {
    //Create the XmlNamespaceManager.
    NameTable nt = new NameTable();
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);

    //Add prefix/namespace pairs to the XmlNamespaceManager.
    nsmgr.AddNamespace("", "www.wideworldimporters.com"); //Adds a default namespace.
    nsmgr.AddNamespace("europe", "www.wideworldimporters.com/europe");
    nsmgr.PushScope();  //Pushes a namespace scope on the stack.
    nsmgr.AddNamespace("", "www.lucernepublishing.com"); //Adds another default namespace.
    nsmgr.AddNamespace("partners", "www.lucernepublishing.com/partners");

    Console.WriteLine("Show all the prefix/namespace pairs in the XmlNamespaceManager...");
    ShowAllNamespaces(nsmgr);
  }

  private void ShowAllNamespaces(XmlNamespaceManager nsmgr)
  {
    do{
       foreach (String prefix in nsmgr)
       {
        Console.WriteLine("Prefix={0}, Namespace={1}", prefix,nsmgr.LookupNamespace(prefix));
       } 
    }
    while (nsmgr.PopScope());
  }
}

    

Return to top


Method: PushScope()
Summary
Pushes a namespace scope onto the stack.
C# Syntax:
public virtual void PushScope();
Remarks
After a call to this method all namespaces, which are added to XmlNamespaceManager (by calling XmlNamespaceManager.AddNamespace), belong to the pushed namespace scope.
Example
The following example adds prefix/namespace pairs to the XmlNamespaceManager and then displays all the pairs in the collection.


using System;
using System.IO;
using System.Xml;


public class Sample
{
  public static void Main()
  {
    Sample test = new Sample();
  }
  public Sample()
  {
    //Create the XmlNamespaceManager.
    NameTable nt = new NameTable();
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);

    //Add prefix/namespace pairs to the XmlNamespaceManager.
    nsmgr.AddNamespace("", "www.wideworldimporters.com"); //Adds a default namespace.
    nsmgr.AddNamespace("europe", "www.wideworldimporters.com/europe");
    nsmgr.PushScope();  //Pushes a namespace scope on the stack.
    nsmgr.AddNamespace("", "www.lucernepublishing.com"); //Adds another default namespace.
    nsmgr.AddNamespace("partners", "www.lucernepublishing.com/partners");

    Console.WriteLine("Show all the prefix/namespace pairs in the XmlNamespaceManager...");
    ShowAllNamespaces(nsmgr);
  }

  private void ShowAllNamespaces(XmlNamespaceManager nsmgr)
  {
    do{
       foreach (String prefix in nsmgr)
       {
        Console.WriteLine("Prefix={0}, Namespace={1}", prefix,nsmgr.LookupNamespace(prefix));
       } 
    }
    while (nsmgr.PopScope());
  }
}

    

Return to top


Method: RemoveNamespace(
   string prefix,
   string uri
)
Summary
Removes the given namespace for the given prefix.
C# Syntax:
public virtual void RemoveNamespace(
   string prefix,
   string uri
);
Parameters:

prefix

The prefix for the namespace

uri

The namespace to remove for the given prefix. The namespace removed is from the current namespace scope. Namespaces outside the current scope are ignored. Exceptions are never thrown.

Return to top


Method: ToString()
Inherited
See base class member description: System.Object.ToString
C# Syntax:
public virtual string ToString();

For more information on members inherited from System.Object click on the link above.

Return to top


Top of page

Copyright (c) 2002 Microsoft Corporation. All rights reserved.