2012-12-18 21 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. 普通老式字符串连接
相关问题