2

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.

4
  • Use the Select-Object cmdlet to select output, not Write-Output Commented Aug 3, 2015 at 15:06
  • If I use Select, it just runs with no errors but doesn't write to the screen. I know it's doing something behind the scenes but I'm not sure what. Commented Aug 3, 2015 at 15:11
  • That's because non of the XmlElement's (the childnodes of $xml.Proponix) have a property called ID - your ? filter will never match anything. Use the example in @jisaak's answer Commented Aug 3, 2015 at 15:23
  • Ahh I see now. The example I was looking at had that in the XML file. Thanks for the clarification. Commented Aug 3, 2015 at 15:43

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. This works. How would I take the individual parts and build the string and rename the file?
I will write you that example tomorrow, have to go now
Thank you. I was actually playing around with string concatenation using the -f format modifier but I couldn't get it working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.