XmlNamespaceManager.AddNamespace(String, String) Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Adiciona o namespace dado à coleção.
public:
virtual void AddNamespace(System::String ^ prefix, System::String ^ uri);
public virtual void AddNamespace(string prefix, string uri);
abstract member AddNamespace : string * string -> unit
override this.AddNamespace : string * string -> unit
Public Overridable Sub AddNamespace (prefix As String, uri As String)
Parâmetros
- prefix
- String
O prefixo a associar ao namespace que está a ser adicionado. Use String.Empty para adicionar um namespace predefinido.
Nota Se o XmlNamespaceManager will for usado para resolver namespaces numa expressão XML Path Language (XPath), deve ser especificado um prefixo. Se uma expressão XPath não incluir um prefixo, assume-se que o namespace Uniform Resource Identifier (URI) é o namespace vazio. Para mais informações sobre expressões XPath e os XmlNamespaceManager, consulte os SelectNodes(String) métodos e SetContext(XmlNamespaceManager) .
- uri
- String
O espaço de nomes a acrescentar.
Exceções
O valor de prefix é "xml" ou "xmlns".
O valor para prefix ou uri é null.
Exemplos
O exemplo seguinte é usado XmlNamespaceManager para resolver namespaces num fragmento XML.
using System;
using System.Xml;
public class Sample
{
public static void Main()
{
XmlTextReader reader = null;
try
{
// Create 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>";
// 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 and the
// XmlNamespaceManager to use for namespace resolution.
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 XmlTextReader(xmlFrag, XmlNodeType.Element, context);
// Parse the file and display the node values.
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);
}
}
finally
{
if (reader != null)
reader.Close();
}
}
} // End class
Imports System.Xml
Public Class Sample
Public Shared Sub Main()
Dim reader As XmlTextReader = Nothing
Try
' Create the string containing the XML to read.
Dim xmlFrag As 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>"
' Create an XmlNamespaceManager to resolve namespaces.
Dim nt As NameTable = New NameTable()
Dim nsmgr As XmlNamespaceManager = 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 and the
' XmlNamespaceManager to use for namespace resolution.
Dim context As XmlParserContext
Dim subset As String = "<!ENTITY h 'hardcover'>"
context = New XmlParserContext(nt, nsmgr, "book", Nothing, Nothing, subset, Nothing, Nothing, XmlSpace.None)
' Create the reader.
reader = New XmlTextReader(xmlFrag, XmlNodeType.Element, context)
' Parse the file and display the node values.
While (reader.Read())
If (reader.HasValue) Then
Console.WriteLine("{0} [{1}] = {2}", reader.NodeType, reader.Name, reader.Value)
Else
Console.WriteLine("{0} [{1}]", reader.NodeType, reader.Name)
End If
End While
Finally
If Not (reader Is Nothing) Then
reader.Close()
End If
End Try
End Sub
End Class
Observações
XmlNamespaceManager não verifica prefix e uri para a conformidade.
XmlReader verifica nomes, incluindo prefixos e espaços de nomes, para garantir que são nomes XML válidos de acordo com a especificação de Namespaces do World Wide Web Consortium (W3C). XmlNamespaceManager é usado internamente por XmlReader, por isso, para evitar duplicação de esforços, XmlNamespaceManager assume que todos os prefixos e namespaces são válidos.
Se o prefixo e o espaço de nomes já existirem dentro do âmbito atual, o novo par de prefixo e espaço de nomes substituirá a combinação existente de prefixo/espaço de nomes. A mesma combinação de prefixo e namespace pode existir em diferentes escopos.
Os seguintes pares prefixo/espaço de nomes são adicionados por defeito ao XmlNamespaceManager. Podem ser determinados em qualquer escala.
| Prefixo | Namespace |
|---|---|
| xmlns | http://www.w3.org/2000/xmlns/ (o espaço de nomes do prefixo xmlns) |
| xml | http://www.w3.org/XML/1998/namespace (o espaço de nomes XML) |
| String.Empty | String.Empty (o espaço de nomes vazio). Este valor pode ser reatribuído a um prefixo diferente. Por exemplo, xmlns="" define o namespace padrão como o namespace vazio |