-
Filtering XML Child Elements in PowerShell
Posted on September 28th, 2012 3 commentsRecently I was working with some XML documents along the lines of the following. Each set of data had some common elements, Name and Description and other elements based around a pattern, Filepathx.
<?xml version="1.0" encoding="utf-8"?> <dataset> <data> <Name>Test1</Name> <Description>First test in the set</Description> <FilePath4>C:\Application\Apple.txt</FilePath4> <FilePath7>C:\Test\Orange.txt</FilePath7> </data> <data> <Name>Test2</Name> <Description>Second test in the set</Description> <FilePath12>C:\Application\Banana.txt</FilePath12> <FilePath3>C:\Test\Pear.txt</FilePath3> </data> </dataset>
I needed to check the path for any of these that were present in each dataset. Working with XML files in PowerShell is pretty straightforward. For instance to work with the above file you could start with:
$xml = [ xml ](Get-Content .\Test.xml)
and drill down into the data with
$xml.dataset.data
but how would you pick out those columns based on the header name of FilePathx, that could not be predicted and would vary each time both in the number of them and the x element?
I can return and filter the property names with Get-Member, but how to then access the child elements?
$xml.dataset.data | Get-Member -MemberType Property | where {$_.name -like 'FilePath*'}Turns out that the object we are working with System.Xml.XmlElement has a ChildNodes property, but you don’t see that by piping the object into Get-Member, only if you view the MSDN page. However, if you use the Force parameter then you will see a get_childnodes method which will give you a hint that a ChildNodes property exists, but PowerShell is not exposing it via Get-Member.
$xml.dataset.data | Get-Member -Force
So now we can filter the data how we need to:
$xml.dataset.data | select -ExpandProperty childnodes | where {$_.name -like 'FilePath*'}and if I pick out a suitable property I can carry out the necessary test of whether the file exists.
$xml.dataset.data | select -ExpandProperty childnodes | where {$_.name -like 'FilePath*'} | select -ExpandProperty InnerText | Test-Path3 responses to “Filtering XML Child Elements in PowerShell”

-
is there supposed to be a “1″ in the first command?
$xml = 1(Get-Content .\Test.xml)
i get an error if i do that.
if i leave the 1 out, it seems to import ok, as $xml returns the contents of the file.
however nothing else works.
$xml.dataset.data returns nothing.
what might i be doing wrong?
-
Curtiss March 19th, 2013 at 15:53
found it. the first line is supposed to read
$xml = (Get-Content .\Test.xml)
Leave a reply
-














Curtiss March 19th, 2013 at 15:43