Mitchell
Mitchell

Reputation: 7087

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..

Upvotes: 3

Views: 874

Answers (2)

StuartLC
StuartLC

Reputation: 107247

There a couple of issues (And also assuming you've just snipped the Xml sample as the elements don't close)

Package (and hence Identity) are in an xmlns "http://schemas.microsoft.com/appx/2010/manifest" - you'll need another namespace.

nsmgr.AddNamespace("def", "http://schemas.microsoft.com/appx/2010/manifest")

Also, your attribute xpath doesn't look correct. Scrape the values of the attributes like so:

PackageID = xml.SelectSingleNode("//def:Package/def:Identity/@appv:PackageId", 
                                 nsmgr).Value
PackageID = xml.SelectSingleNode("//def:Package/def:Identity/@appv:VersionId", 
                                 nsmgr).Value

Upvotes: 1

Christian Hayter
Christian Hayter

Reputation: 31071

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".

Upvotes: 1

Related Questions