【问题标题】:Getting data between XML comments with powershell使用 powershell 在 XML 注释之间获取数据
【发布时间】:2014-04-22 04:33:18
【问题描述】:

我希望能够识别(和替换)XML cmets 之间的 XML 元素。例如:

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

我使用 cmets 的原因是因为这是来自 .NET Web 项目的 web.config 文件。我不使用自定义配置部分的原因是该应用程序已有多年历史,并且有数千个对这些键的现有引用,因此更改它们的访问方式可能很麻烦。

【问题讨论】:

  • 所以您可以控制备注在文件中的位置?
  • 是的,我可以确保它们在正确的位置(即不跨越标签或其他东西)。
  • 所以我个人会为我想要抓取的标签添加一个属性。这将使您更容易获得您想要的 imo。

标签: xml powershell


【解决方案1】:

这可能不是最佳的,但它确实有效。这里有两个常量,字符串和文件名。

$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 }
}

作为替代方案:

$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)

【讨论】:

    猜你喜欢
    • 2023-02-01
    • 2011-08-31
    • 1970-01-01
    • 2020-12-30
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    相关资源
    最近更新 更多