我有以下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;
}
我喜欢的是给对象周围的<Property>
标记起一个名字。
例如:
<?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很陌生,很乐意在这里得到一些帮助。
到目前为止我尝试了什么:
我还考虑过简单地在对象中添加另一个Property,然后将其命名为name="CustomerInformation"
并让我清空,但如果它位于对象的顶层会更好。
答案 0 :(得分:1)
将该自定义对象嵌套在另一个自定义对象中:
$customerInformation = [PSCustomObject]@{
'CustomerInformation' = [PSCustomObject]@{
'CustomerName' = $CustomerName
'Environment' = $Environment
'isVdi' = $isVdi
}
}
然后转换该结构:
$xml = $customerInformation | ConvertTo-Xml -Depth 2
但请注意,您必须添加参数-Depth
,其值为&gt; 1才能生效。该参数的默认值为1,这将导致以下错误,因为它没有转换整个对象层次结构:
ConvertTo-Xml : Unexpected end of file has occurred. The following elements are not closed: Object, Objects. Line 7, position 16. At line:1 char:31 + $xml = $customerInformation | ConvertTo-Xml + ~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [ConvertTo-Xml], XmlException + FullyQualifiedErrorId : System.Xml.XmlException,Microsoft.PowerShell.Commands.ConvertToXmlCommand