2012-12-18 22 views
0

我有以下Powershell腳本。使用自定義元素標記名稱將數組轉換爲xml

$load = @(@(1, 2), @(3)) 
$Load | % { "[$_]" } 
$Date = Get-Date "2012-01-01" 
$xml = $Load | ConvertTo-Xml -NoTypeInformation 
$xml.OuterXml 

該代碼生成以下結果。

[1 2] 
[3] 
<?xml version="1.0"?> 
<Objects> 
    <Object> 
    <Property>1</Property> 
    <Property>2</Property> 
    </Object> 
    <Object> 
    <Property>3</Property> 
    </Object> 
</Objects> 

但是我希望能夠到指定的XML元素的名稱,並添加一個額外的Date(常量)元素。這是一個簡單的方法來做到這一點?

<?xml version="1.0"?> 
<Groups> 
    <Group> 
    <Item><ID>1</ID><Date>2012-01-01</Date></Item> 
    <Item><ID>2</ID><Date>2012-01-01</Date></Item> 
    </Group> 
    <Group> 
    <Item><ID>3</ID><Date>2012-01-01</Date></Item> 
    </Group> 
</Groups> 

我嘗試了下面的「新對象」方法,但結果非常冗長,而不是我想要的。

$load = @(@(1, 2), @(3)) 
$Load | % { "[$_]" } 
$Date = Get-Date "2012-01-01" 
$xml = $Load | 
    % { 
     @(, @{ ID = $_; Date = $Date }) 
    } | 
    ConvertTo-Xml -NoTypeInformation 
$xml.OuterXml 
+0

看看我的回答對這個[問題] [1]。 [1]:http://stackoverflow.com/questions/13751230/append-data-into-existing-xml-file-via-powershell/13751693#13751693 – D3vtr0n

回答

0

兩個解決方案:

  1. Select-Xml
  2. 普通老式字符串連接
相關問題