0
votes

I am trying to create xml file using powershell, and it add an empty xmlns="" in my second layer of node. Google saided that it's because the namespace is different between parent and child, how can I make them same when generating?

My powershell code is below

$gNamespace = "http://schemas.microsoft.com/wix/2006/wi"
$xmlFilePath = "PATH_TO_XML_FILE"
$xmlWriter = New-Object System.XMl.XmlTextWriter($xmlFilePath, $Null)
$xmlWriter.Formatting = 'Indented'
$xmlWriter.Indentation = 1
$XmlWriter.IndentChar = "`t"
$xmlWriter.WriteStartDocument()
$xmlWriter.WriteStartElement("Wix", $gNamespace)
$xmlWriter.WriteEndElement()
$xmlWriter.WriteEndDocument()
$xmlWriter.Finalize
$xmlWriter.Flush()
$xmlWriter.Close()

$xmlDoc = [System.Xml.XmlDocument](Get-Content $xmlFilePath);
$nsmgr = new-object System.Xml.XmlNamespaceManager($xmlDoc.NameTable)
$nsmgr.AddNamespace("wixns", $gNamespace)

$xmlDoc = [System.Xml.XmlDocument](Get-Content $xmlFilePath)
$productNode = $xmlDoc.CreateElement("Product")
$xmlDoc.SelectSingleNode("//wixns:Wix", $nsmgr).AppendChild($productNode)
$productNode.SetAttribute("Id", "ProductIdHere")

The code above generate the following xml

<?xml version="1.0"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <Product Id="ProductIdHere" xmlns=""/>
</Wix>

My expected result is

<?xml version="1.0"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <Product Id="ProductIdHere"/>
</Wix>

How to make the namespace the same between parent and child when generating the xml by powershell? and also select the correct node with namespace?

Thanks for your help.

1

1 Answers

1
votes

There are much simpler ways of how to do that in PowerShell. Have a look at this example here

From this you can create your XML e.g. as follows:

[xml]$doc = New-Object System.Xml.XmlDocument
$dec = $doc.CreateXmlDeclaration("1.0", $null, $null)
$doc.AppendChild($dec)  
$root = $doc.CreateNode("element","WiX", "http://schemas.microsoft.com/wix/2006/wi")
$c = $doc.CreateNode("element", "Product", "http://schemas.microsoft.com/wix/2006/wi")
$c.SetAttribute("Id", "ProductIdHere") | Out-Null
$root.AppendChild($c) | Out-Null
$doc.AppendChild($root) | Out-Null
$doc.Save($pathToSave)

You could of course also just store a base structure in either a string or file, then cast it as [xml] and from then on perform some manipulation.