2

I'm trying to parse following XML from a file using Powershell without actually loading it as XML document using [xml] since the document contain errors.

<data>
  <company>Walter & Cooper</company>
  <contact_name>Patrick O'Brian</contact_name>
</data>

To load document successfully I need to fix errors by replacing special characters as follows

& with &amp;
< with &lt;
' with &apos; etc..

I know I could do something like this to find and replace characters in a document

(Get-Content $fileName) | Foreach-Object {
  $_-replace '&', '&amp;' `
    -replace "'", "&apos;" `
    -replace '"', '&quot;'} | Set-Content $fileName

But this will replace characters everywhere in the file, I'm only interest in checking for characters inside xml tags like <company> and replacing them with xml safe entities so that resultant text is a valid document which I can load using [xml].

2 Answers 2

2

Something like this should work for each character you need to replace:

$_-replace '(?<=\W)(&)(?=.*<\/.*>)', '&amp' `
  -replace '(?<=\W)(')(?=.*<\/.*>)', '&apos;' `
  -replace '(?<=\W)(")(?=.*<\/.*>)', '&quot;' `
  -replace '(?<=\W)(>)(?=.*<\/.*>)', '&gt;' `
  -replace '(?<=\W)(\*)(?=.*<\/.*>)', '&lowast;' } | Set-Content $fileName

which does a positive look-behind with a non-word character, then the capturing group followed by a positive look-ahead.

examples:

updated: http://regex101.com/r/aY8iV3 | original: http://regex101.com/r/yO7wB1

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this works great but fails with < and > symbols also in a corner case where any special character appear between >< inside tag values. <company>Failure Test Case &*>"<'_@</company>
@Raj - For the symbols < > you could do a positive look-behind with a non-word char \W and then continue with the capturing group with a positive look-ahead. I've updated the answer/example.
1

A little bit of regex look-behind and look-ahead should do the trick:

$str = @'
<data>
  <company>Walter & Cooper & Brannigan</company>
  <contact_name>Patrick & O'Brian</contact_name>
</data>
'@

$str -replace '(?is)(?<=<company>.*?)&(?=.*?</company>)', '&amp;'

Comments

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.