【问题标题】:Name property in ConvertTo-XMLConvertTo-XML 中的名称属性
【发布时间】:2018-02-01 08:52:08
【问题描述】:

我有以下 XML 输出:

<?xml version="1.0" encoding="utf-8"?>
<Objects>
  <Object>
    <Property>
      <Property Name="CustomerName">MyCustomerName</Property>
      <Property Name="Environment">Integration</Property>
      <Property Name="isVdi">false</Property>
    </Property>
    <!-- ... (Continues here, but I cut if off since it has nothing to do with the problem) -->
  </Object>
</Objects>

我通过以下方式生成此代码:

$customerInformation = [PSCustomObject]@{
    CustomerName = $CustomerName;
    Environment  = $Environment;
    isVdi        = $isVdi;
}

我希望为对象周围的&lt;Property&gt; 标签命名。

例如:

<?xml version="1.0" encoding="utf-8"?>
<Objects>
  <Object>
    <Property Name="CustomerInformation"> //Here I want to add the "CustomerInformation"
      <Property Name="CustomerName">MyCustomerName</Property>
      <Property Name="Environment">Integration</Property>
      <Property Name="isVdi">false</Property>
    </Property>
  </Object>
</Objects>

但我不知道该怎么做。我什至不确定它是否可能,或者我是否必须使用type 属性。我对 XML 有点陌生,很乐意在这里获得一些帮助。

到目前为止我所做的尝试:

  • 已尝试通过 Google 寻找解决方案。
  • 尝试手动创建 XML(可能可行,但不是我真正想要的,因为维护干净的代码会变得越来越复杂

我还考虑过简单地将另一个属性添加到对象中,然后将其命名为 name="CustomerInformation" 并让我为空,但如果它位于对象的顶层会更好。

【问题讨论】:

    标签: xml powershell pscustomobject


    【解决方案1】:

    将该自定义对象嵌套在另一个自定义对象中:

    $customerInformation = [PSCustomObject]@{
        'CustomerInformation' = [PSCustomObject]@{
            'CustomerName' = $CustomerName
            'Environment'  = $Environment
            'isVdi'        = $isVdi
        }
    }
    

    然后转换该结构:

    $xml = $customerInformation | ConvertTo-Xml -Depth 2
    

    但请注意,您必须添加参数-Depth,其值>1 才能正常工作。该参数的默认值为 1,这将导致以下错误,因为它没有转换整个对象层次结构:

    ConvertTo-Xml : 文件意外结束。以下元素是 未关闭:对象,对象。第 7 行,第 16 位。 在行:1 字符:31 + $xml = $客户信息 |转换为 XML + ~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [ConvertTo-Xml], XmlException + FullyQualifiedErrorId:System.Xml.XmlException,Microsoft.PowerShell.Commands.ConvertToXmlCommand

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      • 2015-05-26
      • 2012-01-21
      • 1970-01-01
      相关资源
      最近更新 更多