如何在PowerShell中添加XML名称空间作为属性前缀?

问题描述 投票:1回答:1

我想使用Powershell v3生成以下XML

<?xml version="1.0" encoding="UTF-8"?>
<AMXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://registration.somewhere.com/schemas/something.xsd">
  <Type>Something</Type>
</AMXML>

到目前为止我已经得到了以下代码

[xml]$doc = New-Object System.Xml.XmlDocument
$dec = $doc.CreateXmlDeclaration("1.0", "UTF-8", $null)
$doc.AppendChild($dec) | Out-Null

$root = $doc.CreateNode("element","AMXML",$null)

$att = $doc.CreateAttribute("xmlns:xsi")
$att.Value = "http://www.w3.org/2001/XMLSchema-instance"
$root.Attributes.Append($att) | Out-Null

$att1 = $doc.CreateAttribute("xsi:noNamespaceSchemaLocation")
$att1.Value = "http://registration.somewhere.com/schemas/something.xsd"
$root.Attributes.Append($att1) | Out-Null

$x = $doc.CreateNode("element", "Type", $null)
$x.InnerText = "Something"
$root.AppendChild($x) | Out-Null

$doc.AppendChild($root) | Out-Null

$doc.InnerXml

哪个产生

<?xml version="1.0" encoding="UTF-8"?>
<AMXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" noNamespaceSchemaLocation="http://registration.somewhere.com/schemas/something.xsd">
  <Type>Something</Type>
</AMXML>

尽管创建属性xsi:noNamespaceSchemaLocation,输出将删除xsi:前缀,只留下noNamespaceSchemaLocation="http://registration.some where.com/schemas/something.xsd",这使我的xsd失败。

我尝试了CreateAttribute()的各种重载,导致额外的属性或交换的前缀。

我哪里错了?

xml powershell xsd
1个回答
1
投票

您需要在xsi名称空间中创建该属性:

$xsi_uri = 'http://www.w3.org/2001/XMLSchema-instance'

$att1 = $doc.CreateAttribute('xsi', 'noNamespaceSchemaLocation', $xsi_uri)
$att1.Value = "http://registration.somewhere.com/schemas/something.xsd"
$root.Attributes.Append($att1) | Out-Null
© www.soinside.com 2019 - 2024. All rights reserved.