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

时间:2018-02-02 12:13:21

标签: xml powershell xsd

我想使用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()的各种重载,这会导致额外的属性或交换的前缀。

我哪里错了?

1 个答案:

答案 0 :(得分:2)

您需要在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