【问题标题】:Convert an array to xml with customized element tag name使用自定义元素标签名称将数组转换为 xml
【发布时间】:2012-12-05 08:27:30
【问题描述】:

我有以下 Powershell 脚本。

$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(constant) 元素。这是一种简单的方法吗?

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

【问题讨论】:

标签: powershell


【解决方案1】:

两种解决方案:

  1. Select-Xml
  2. 普通的旧字符串连接

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    • 2017-12-25
    相关资源
    最近更新 更多