Created
October 30, 2017 23:05
-
-
Save aadennis/7fcb5ab339d0fd69f9a04a48cde6a94a to your computer and use it in GitHub Desktop.
Walk an XML file, updating key values pairs based on a given pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Having generated well-formed but invalid xml from bsa xsd, the tool that gen'd the sample xml | |
# may have duplicated e.g. SeqNum. | |
# This takes an input file ($inFile), makes the SeqNum values unique, and writes to a random named | |
# file in c:/temp ($outFile). | |
# Now when you validate e.g. in Visual Studio or XMLSpy, the SeqNum will pass (even if plenty else is wrong.) | |
function Set-ReplacementString($templateStart, [int] $valueToUpdate, $templateEnd) { | |
"$templateStart$valueToUpdate$templateEnd" | |
} | |
$inFile = Get-Content -Path C:\temp\x.xml | |
$inFile.Length | |
$pattern = "SeqNum=`".*`"" # "any and all characters within the double quotes are ignored for pattern-matching (in addition to SeqNum etc having to match) | |
$updatedPatternStart = "SeqNum=`"" | |
$updatedPatternEnd = "`"" | |
$r = [regex] $pattern | |
$currentSequenceNumber = 1 | |
$filePrefix = Get-Random -Minimum 1 -Maximum 999999 | |
$filePrefix | |
$outFile = "c:\temp\bsa_$filePrefix.xml" | |
$outFile | |
$inFile | ForEach-Object { | |
$currentLine = $_ | |
$result = $r.Match($currentLine) | |
if ($result.Success) { | |
$foundLiteral = $result.Value | |
# So $result.Value now becomes the literal string we want to replace | |
"Found a pattern match: $foundLiteral" | |
$replacementString = Set-ReplacementString $updatedPatternStart $currentSequenceNumber $updatedPatternEnd | |
$updatedLine = $currentLine -replace $foundLiteral, $replacementString | |
$updatedLine | |
$currentSequenceNumber++ | |
$updatedLine | Out-File -FilePath $outFile -Append | |
} else { | |
$currentLine | Out-File -FilePath $outFile -Append | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment