3

I want to generate the following XML using Powershell v3

<?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>

and I've got the following code so far

[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

Which produces

<?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>

Despite creating the attribute xsi:noNamespaceSchemaLocation the output removes the xsi: prefix, leaving just noNamespaceSchemaLocation="http://registration.some where.com/schemas/something.xsd" which fails my xsd.

I've tried various overloads of CreateAttribute() which results in extra attributes or swapped prefixes.

Where am I going wrong?

1 Answer 1

4

You need to create the attribute in the xsi namespace:

$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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.