Search code examples
xmlpowershellxdt-transform

xdt with powershell


Actually i dont have much knowledge about xtd-transform. What i need in my xdt file :

<add key="EndpointName" value="SomeValue" xdt:Transform="SetAttributes(value)" xdt:Locator="Match(key)" />

routine work that im doing in powershell :

$cache.SetAttribute("key","EndpointName")
$cache.SetAttribute("value","SomeValue")
$cache.SetAttribute("xdt:Transform","SetAttributes(value)")
$cache.SetAttribute("xdt:Locator","Match(key)")

And here are what i have. Dont match my points:

<add key="EndpointName" value="Email" Transform="SetAttributes(value)" Locator="Match(key)" />

So is it possible to create xdt:attribute using powershell scripts?

Thanks guys!


Solution

  • When XML namespaces are involved you need to use an XmlNamespaceManager e.g.:

    $xdt = 'http://schemas.microsoft.com/XML-Document-Transform'
    $xml = [xml]"<doc xmlns:xdt='$xdt'><add key='foo' value='foo' xdt:Transform='foo' xdt:Locator='foo'/></doc>"
    
    $nsmgr = new-object Xml.XmlNamespaceManager $xml.NameTable
    $nsmgr.AddNamespace("xdt", $xdt)
    
    $xml.doc.add.SetAttribute('Transform', $xdt, 'SetAttribute(value)') > $null
    

    Results in:

    <doc xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
      <add key="foo" value="foo" xdt:Transform="SetAttribute(value)" xdt:Locator="foo" />
    </doc>