2

I want to be able to be able to identify (and replace) XML elements between XML comments. E.g:

<!-- between here -->
<add key="userdefined1" value="something1" />
<add key="userdefined2" value="something2" />
<add key="userdefined3" value="something3" />
<!-- between here -->

The reason I'm using comments is because this is the web.config file from a .NET web project. The reason I'm not using custom config sections is that the application is years old and there are thousands of existing refernces to these keys so changing the way they're accessed could be a hassle.

3
  • So you have control over where the remarks get put in the file? Commented Aug 17, 2012 at 18:56
  • Yes, I can ensure they're in the right place (i.e. not straddling tags or something). Commented Aug 17, 2012 at 19:49
  • 1
    So personally I would add an attribute to the tags that I want to grab. That would make it much easier to get the ones you want imo. Commented Aug 17, 2012 at 20:35

1 Answer 1

1

This may not be optimal, but it works. You have two constants here, the string and the filename.

$comment = '<!-- between here -->'
$start = $false
ForEach ($l in (Get-Content .\testfile.config)) { 
        if (-not $start -and $l -notmatch $comment) {continue}
        if (-not $start -and $l -match $comment ) { $start = $True }
        elseif ($start -and  $l -notmatch $comment) { echo $l }
        elseif ($start -and  $l -match $comment) { break }
}

As an alternative:

$comment = '<!-- between here -->'
$file = '.\testfile.config'
Select-String -pattern $comment -path $file | % { if (-not $b) { $b=$_.LineNumber} else { $e=$_.LinenUmber-2}}
Get-Content $file | Select-Object -Index ($b..$e)
Sign up to request clarification or add additional context in comments.

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.