Search code examples
xmlvb.netxpathxmldocument

Reading XML properties using vb.net with XPATH


Im trying to create a application that reads properties of a appv manifest file. I use vb.net 2012 for the application.

I want to read the property: 'VersionId' and 'PackageId' from the manifest file using xpath, but i cant understand the way that XPATH is working.

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns:appv1.1="http://schemas.microsoft.com/appv/2013/manifest" xmlns:appv="http://schemas.microsoft.com/appv/2010/manifest" xmlns="http://schemas.microsoft.com/appx/2010/manifest" appv:IgnorableNamespaces="appv1.1" IgnorableNamespaces="appv appv1.1">
<Identity appv:VersionId="79cdb3a0-8f7d-416d-828e-003fe3125eb2" appv:PackageId="64ce44eb-5255-4514-bb74-e14ae393ae9a" Version="0.0.0.4" Publisher="CN=Reserved" Name="Reserved"/>

This is what I have now:

Dim xml As New XmlDocument
xml.Load(xmlFileName)
Dim nsmgr As New XmlNamespaceManager(xml.NameTable)
nsmgr.AddNamespace("appv", "http://schemas.microsoft.com/appv/2010/manifest")
PackageID = xml.SelectSingleNode("//Package/Identity[@name='appv:PackageId']", nsmgr).InnerText
VersionID = xml.SelectSingleNode("//Package/Identity[@name='appv:VersionId']'", nsmgr).InnerText

Please help.. its driving me totally crazy..


Solution

  • The default namespace is not blank, so you must define and use an explicit namespace prefix for the default namespace in your XPath expressions. For example:

    Dim xml As New XmlDocument
    xml.Load(xmlFileName)
    Dim nsmgr As New XmlNamespaceManager(xml.NameTable)
    nsmgr.AddNamespace("appv", "http://schemas.microsoft.com/appv/2010/manifest")
    nsmgr.AddNamespace("appx", "http://schemas.microsoft.com/appx/2010/manifest")
    PackageID = xml.SelectSingleNode("//appx:Package/appx:Identity[@name='appv:PackageId']", nsmgr).InnerText
    VersionID = xml.SelectSingleNode("//appx:Package/appx:Identity[@name='appv:VersionId']'", nsmgr).InnerText
    

    To put it another way, the absence of a namespace prefix in an XML document means "the default namespace", whereas the absence of a namespace prefix in an XPath query means "the blank namespace".