Udostępnij za pośrednictwem


Using SelectSingleNode in PowerShell with XML Namespace (Azure VNetConfig)

So, been doing a lot of work in Azure lately and having to solve problems I have not had to deal with before.  As you know the Network Configuration for Azure if not done through the portal is done through an XML file. Below is an example of an XML file exported from Azure with the command get-azurevnetconfig –ExportToFile c:\test\network.xml

 <?xml version="1.0" encoding="utf-8"?>
<NetworkConfiguration  >
  <VirtualNetworkConfiguration>
    <Dns />
    <VirtualNetworkSites>
      <VirtualNetworkSite name="test" Location="East US">
        <AddressSpace>
          <AddressPrefix>192.168.1.0/24</AddressPrefix>
        </AddressSpace>
        <Subnets>
          <Subnet name="Subnet-1">
            <AddressPrefix>192.168.1.0/24</AddressPrefix>
          </Subnet>
         </Subnets>
      </VirtualNetworkSite>
     </VirtualNetworkSites>
  </VirtualNetworkConfiguration>
</NetworkConfiguration> 

So let’s say you want to update the AddressPrefix for the Virtual Network Site test. So you load the xml file into a variable. [xml] $azurenetconfig = get-content -path "$PWD\network.xml"

With PowerShell and XML you should be able to run the following command and get data back. But you get no data back… why is that?

$network.SelectSingleNode("//VirtualNetworkSite[@name='test']")

image

By reading MSDN https://msdn.microsoft.com/en-us/library/h0hw012b(v=vs.110).aspx you can see that when dealing with XML that has a namespace you must specify the namespace.

So for this command to work we must define the namespace, that is done in the commands below.

 $ns = New-Object System.Xml.XmlNamespaceManager($network.NameTable)
$ns.AddNamespace("ns", $network.DocumentElement.NamespaceURI)

Now we need to run the same SelectSingleNode method but with the namespace defined.

$network.SelectSingleNode("//ns:VirtualNetworkSite[@name='test']", $ns)

Now you can see we actually get data back.  Hope this helps someone that might be struggling with this or leveraging any XML with a namespace

image

Comments

  • Anonymous
    January 01, 2003
    Thanks for the article
  • Anonymous
    May 13, 2015
    Thanks a lot, This article saved my day :)
  • Anonymous
    October 15, 2015
    Good Article you have posted. Thanks for sharing.
  • Anonymous
    April 18, 2016
    Lifesaver!
  • Anonymous
    April 18, 2016
    Super article, saved lot of efforts