Using [System.Xml.XmlTextWriter] in combination with [System.IO.StringWriter] you can easily create an arbitrary large XML document in memory on the fly. Creating and closing elements and attributes comes down to a simple pair of WriteStartelement()/WriteEndelement() and WriteAttributeString().
However when you want to create namespaces in your XML document things get a little bit trickier as the accompanying MSDN documentation for WriteAttributeString() is misleading.
It reads:

public void WriteAttributeString(
 string prefix,
 string localName,
 string ns,
 string value

… implying you could use a corresponding PowerShell statement like this:

 $XmlWriter.WriteAttributeString("xmlns", "xsi", $null, "");

Exception calling "WriteAttributeString" with "4" argument(s): "The 'xmlns' attribute is bound to the reserved
namespace ''."
At line:1 char:1
+ $XmlWriter.WriteAttributeString("xmlns", "xsi", $null, " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
 + FullyQualifiedErrorId : ArgumentException 

Reading the error message you find, that you have to supply the ‘xmlns’ namespace as well instead of passing ‘$null’ (contradicting with the example code).

 $XmlWriter.WriteAttributeString("xmlns", "xsi", "", 

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.