首页 > 解决方案 > 如何使用 powershell 创建一种 XML 结构的多种变体?

问题描述

所以我的主要目标是能够创建 XML 元素的多个变体(如果可能,使用 powershell)。例如下面的xml结构:

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>

</note>

问题 1:有没有办法将整个结构保存在一个变量中?

问题 2:我将如何“保存”该结构并仅通过一项修改创建该结构的多个副本,例如将 Jani 更改为 cody 和 John?我希望能够随意制作该结构的修改副本,但不知道从哪里开始。

任何帮助表示赞赏。谢谢!

标签: xmlpowershell

解决方案


使用带有占位符的 Here-String 。

$xmlTemplate = @"
<note>
    <to>{0}</to>
    <from>{1}</from>
    <heading>{2}</heading>
    <body>{3}</body>
</note>
"@

然后使用它来创建任意数量的这些 xml 片段。占位符{0}等使用Format 运算符{1}获取其真实值,例如:-f

# this demo uses an array of Hashtables
$messages = @{To = 'Tove'  ; From = 'Jani'; Heading = 'Reminder'    ; Body = "Don't forget me this weekend!"},
            @{To = 'Bloggs'; From = 'Cody'; Heading = 'Cancellation'; Body = "No can do!"},
            @{To = 'Doe'   ; From = 'John'; Heading = 'Information' ; Body = "How about next weekend?"}

$messages.GetEnumerator() | ForEach-Object {
    $xmlTemplate -f $_.To, $_.From, $_.Heading, $_.Body 
}

结果:

<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>
<note>
    <to>Bloggs</to>
    <from>Cody</from>
    <heading>Cancellation</heading>
    <body>No can do!</body>
</note>
<note>
    <to>Doe</to>
    <from>John</from>
    <heading>Information</heading>
    <body>How about next weekend?</body>
</note>

推荐阅读