PowerShell: Simple XPath Generator
Introduction
XML is platform and development language independent mode of data storage and exchange. This feature makes XML one of the key mediums for integration of tools, applications and platforms.
Human readable and provides ability to add, update, delete and query data items dynamically by any programming language.
Tree representation of data items in infoset describes an abstract data model.
XML is used to store data and exchange data.
The tree represented by an XML document starts at root element and branches at the lowest level of elements. All elements in an XML document can contain sub-elements, text and attributes as shown below.
XPath:
XPath (XML Path Language) query language is used to navigate XML document to get to specific node or data in an XML file. XPath expressions that can query an XML document for one or more XML data items like elements, attributes, text, etc.
Constructing any XPath for any element or attribute is a tedious job and need to view XML in a tree view. This process becomes more complex in dynamically built XML files.
XPath Syntax:
Refer to below link for XPath syntax.
https://www.w3schools.com/xml/xpath_syntax.asp
Following script dynamically buildsXPathh for given element, attribute and attribute value.
Thanks to PowerShell, Microsoft PowerShell fully supports XML .NET class (System.Xml ) and XPath query. Using PowerShell you can load an XML file and query for data in XML file.
PowerShell command:
Select-XML –Xml <XML file object> -Xpath <Xpath> | foreach {$_.node }
Above command displays data at givenXPathh.
Example:
> [xml]$XmlFileObj = Get-Content 'c:\books.xml'
> Select-Xml -Xml $XmlFileObj -XPath '//book' | foreach{$_.node}
To use above command, need to have XPath. Following script generates XPath for a given Element, Attribute and Attribute value.
Script download link: click here
How to use script:
Syntax:
Run XPath-Generator with full help.
> Help Xpath-Generator -full