Επεξεργασία

Κοινή χρήση μέσω


GetXmlNamespace Operator (Visual Basic)

Gets the XNamespace object that corresponds to the specified XML namespace prefix.

Syntax

GetXmlNamespace(xmlNamespacePrefix)

Parts

xmlNamespacePrefix Optional. The string that identifies the XML namespace prefix. If supplied, this string must be a valid XML identifier. For more information, see Names of Declared XML Elements and Attributes. If no prefix is specified, the default namespace is returned. If no default namespace is specified, the empty namespace is returned.

Return Value

The XNamespace object that corresponds to the XML namespace prefix.

Remarks

The GetXmlNamespace operator gets the XNamespace object that corresponds to the XML namespace prefix xmlNamespacePrefix.

You can use XML namespace prefixes directly in XML literals and XML axis properties. However, you must use the GetXmlNamespace operator to convert a namespace prefix to an XNamespace object before you can use it in your code. You can append an unqualified element name to an XNamespace object to get a fully qualified XName object, which many LINQ to XML methods require.

Example

The following example imports ns as an XML namespace prefix. It then uses the prefix of the namespace to create an XML literal and access the first child node that has the qualified name ns:phone. It then passes that child node to the ShowName subroutine, which constructs a qualified name by using the GetXmlNamespace operator. The ShowName subroutine then passes the qualified name to the Ancestors method to get the parent ns:contact node.

' Place Imports statements at the top of your program.  
Imports <xmlns:ns="http://SomeNamespace">

Module GetXmlNamespaceSample

    Sub RunSample()

        ' Create test by using a global XML namespace prefix. 

        Dim contact = 
            <ns:contact>
                <ns:name>Patrick Hines</ns:name>
                <ns:phone ns:type="home">206-555-0144</ns:phone>
                <ns:phone ns:type="work">425-555-0145</ns:phone>
            </ns:contact>

        ShowName(contact.<ns:phone>(0))
    End Sub

    Sub ShowName(ByVal phone As XElement)
        Dim qualifiedName = GetXmlNamespace(ns) + "contact"
        Dim contact = phone.Ancestors(qualifiedName)(0)
        Console.WriteLine("Name: " & contact.<ns:name>.Value)
    End Sub

End Module

When you call TestGetXmlNamespace.RunSample(), it displays a message box that contains the following text:

Name: Patrick Hines

See also