Matt Williamson
Matt Williamson

Reputation: 7095

Extract parts from XML file using powershell

Given the following XML file structure, why isn't my code working? I just want to extract out those fields so I can rename the XML file like the following:

SB90634111_TYPE_20150803_PAY.xml

<?xml version="1.0"?>
<Proponix>
    <Header>
        <DestinationID>ABC</DestinationID>
        <SenderID>PRO</SenderID>
        <ClientBank>ABC</ClientBank>
        <OperationOrganizationID>ABCD</OperationOrganizationID>
        <MessageType>TYPE</MessageType>
        <DateSent>20150802</DateSent>
        <TimeSent>135244</TimeSent>
        <MessageID>1073459900</MessageID>
    </Header>
    <SubHeader>
        <InstrumentID>SB90634111</InstrumentID>
        <InstrumentStatus>ACT</InstrumentStatus>
        <ActivityType>PAY</ActivityType>
        <BusinessDate>20150803</BusinessDate>  
    </SubHeader>
</Proponix>


$xml = [xml](Get-Content 'my.xml')
$xml.Proponix | ? {$_.ID -eq 'Header'} | write-output MessageType
$xml.Proponix | ? {$_.ID -eq 'Subheader'} | write-output InstrumentID,ActivityType,BusinessDate

I'm running Powershell 2.0 on Windows 7 Pro if that matters.

Upvotes: 2

Views: 2096

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58991

You can access the Header element using $xml.Proponix.Header:

$xml.Proponix.Header | Select MessageType
$xml.Proponix.SubHeader | Select InstrumentID,ActivityType,BusinessDate

Here is the complete example with rename the file using a format string:

$path =  'c:\my.xml'

$xml = [xml](Get-Content $path)

$newFileName = '{0}_{1}_{2}_{3}.xml' -f `
    $xml.Proponix.SubHeader.InstrumentID,
    $xml.Proponix.Header.MessageType, 
    $xml.Proponix.SubHeader.BusinessDate, 
    $xml.Proponix.SubHeader.ActivityType


Rename-Item $path $newFileName

Upvotes: 3

Related Questions