【问题标题】:How do I add XML namespace as attribute prefix in PowerShell?如何在 PowerShell 中添加 XML 命名空间作为属性前缀?
【发布时间】:2018-07-12 22:34:02
【问题描述】:

我想使用 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】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-27
      • 2013-06-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多