3

I need to create this XML:

<?xml version="1.0" encoding="UTF-8"?>
<SRP xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="sample.xsd">

..but while I know how to write the namespace using XMLWriter (eg:

$XmlWriter.WriteAttributeString("xmlns", "xsi", 
"http://www.w3.org/2000/xmlns/", 
"http://www.w3.org/2001/XMLSchema-instance");

..I've been unable to do so in a variable:

[xml]$XML = New-Object System.Xml.XmlDocument
$Declaration=$XML.CreateXmlDeclaration("1.0","UTF-8",$Null)
$XML.AppendChild($Declaration) 

I've tried various combinations of Namespacemanager but to no avail.. it seems a stupid question, but so far I've been unable to replicate it (short of using an here-string with the hardcoded XML and casting it as an XML of course, but I'd prefer to do it the 'proper' way :)

Thanks to everyone reading so far :)

0

1 Answer 1

3

You don't need a namespace manager for this. Just create the nodes/attributes with the correct namespaces and let the XML processor figure out where to put them.

For your example:

$x = New-Object Xml.XmlDocument
$x.AppendChild($x.CreateXmlDeclaration("1.0","UTF-8",$null))

$node = $x.CreateElement("SRP")

$attr = $x.CreateAttribute("xsi","noNamespaceSchemaLocation","http://www.w3.org/2001/XMLSchema-instance")
$attr.Value="schema.xsd"

$node.SetAttributeNode($attr)
$x.AppendChild($node)

$x.OuterXml
Sign up to request clarification or add additional context in comments.

1 Comment

Worked perfectly, the only very minor quirk is that the resulting XML has the xmlns:xsi and xsi:nonamespaceschemalocation inverted... and the application is complaining about the xml not being generated by a valid schema. (I know it's equivalent, so it's application fault in this case.. stil, if there' s work around this, that would be even better) Many thanks!

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.