0

I have a file with content like this:

 <CdtrAgt>
      <FinInstnId>
        <BIC>HANDSESS</BIC>
        <Nm></Nm>
        <PstlAdr>
          <Ctry>SE</Ctry>
        </PstlAdr>
      </FinInstnId>
    </CdtrAgt>
    <Cdtr>
      <Nm> Very long company name here</Nm>
      <PstlAdr>
        <Ctry>SE</Ctry>
        <AdrLine> Very long street address here</AdrLine>
      </PstlAdr>
    </Cdtr>
    <CdtrAcct>

I need to find all occurrences of the Address and Name filed and trim this down to maximum 30 characters. So far I have this:

(Get-Content "P:\Economy\MonBet\Test.xml") |
Foreach-Object {$_ -replace "(?sm)<AdrLine>.*?</AdrLine>","<AdrLine></AdrLine>"} |
Foreach-Object {$_ -replace "(?sm)<Nm>.*?</Nm>","<Nm>$1</Nm>" } |
Out-File "P:\Economy\MonBet\Test2.xml"

But this only find and removes the text. How do I keep part of the text fond by my RegEx and insert it in my replace?

1 Answer 1

2

Unfortunately, you show us only part of the XML file and now it is invalid xml..

Because it is XML, you should not use string replacements on it, because PowerShell is quite capable to handle xml.

If I add the missing root element and the missing closing tags to your example to become:

<root>
    <CdtrAgt>
        <FinInstnId>
        <BIC>HANDSESS</BIC>
        <Nm></Nm>
        <PstlAdr>
            <Ctry>SE</Ctry>
        </PstlAdr>
        </FinInstnId>
    </CdtrAgt>
    <Cdtr>
        <Nm> Very long company name here blah blah blah</Nm>
        <PstlAdr>
            <Ctry>SE</Ctry>
            <AdrLine> Very long street address here blah blah blah</AdrLine>
        </PstlAdr>
    </Cdtr>
    <CdtrAcct></CdtrAcct>
</root>

Then you can update the strings in the specified tags like below:

[xml]$xml = Get-Content -Path "P:\Economy\MonBet\Test.xml" -Raw

$xml.SelectNodes("//Cdtr") | ForEach-Object {
    $value = $_.Nm.Trim()
    $_.Nm = $value.Substring(0, [math]::Min($value.Length, 30)).Trim()
    $value = $_.PstlAdr.AdrLine.Trim()
    $_.PstlAdr.AdrLine = $value.Substring(0, [math]::Min($value.Length, 30)).Trim()
}

$xml.Save("P:\Economy\MonBet\Test_Updated.xml")

Result:

<root>
  <CdtrAgt>
    <FinInstnId>
      <BIC>HANDSESS</BIC>
      <Nm>
      </Nm>
      <PstlAdr>
        <Ctry>SE</Ctry>
      </PstlAdr>
    </FinInstnId>
  </CdtrAgt>
  <Cdtr>
    <Nm>Very long company name here bl</Nm>
    <PstlAdr>
      <Ctry>SE</Ctry>
      <AdrLine>Very long street address here</AdrLine>
    </PstlAdr>
  </Cdtr>
  <CdtrAcct>
  </CdtrAcct>
</root>
Sign up to request clarification or add additional context in comments.

1 Comment

This was super helpful, working exactly as intended. I had no clue about the xml capabilities. Thank you!

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.