简体   繁体   中英

How to create multiple variations of one XML structure using powershell?

so my main goal is to be able to create multiple variations of an XML element (using powershell if possible). For example, the xml structure below:

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

</note>

Question 1: Is there a way to save that entire structure in one variable?

Question 2: How would I "save" that structure and create multiple copies of that structure with only one modification such as changing the Jani to cody and John? I want to be able to make modified copies of that structure at will but don't know where to start.

Any help appreciated. Thank you!

Use a Here-String for that with placeholders.

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

Then use that to create as many of these xml fragments as you like. The placeholders {0} , {1} etc. get their true values using the -f Format operator like:

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

Result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM