0

How would I go about adding a <Description> tag with its value in the following xmla file (xmla = Microsoft Analysis Services) as a sub element in <Object>?

This simply adds it to the end of the file, not under <Object>.

$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("d", $xml.DocumentElement.NamespaceURI)
$xml.SelectSingleNode("//d:Database/d:Description", $ns)

$xmlElt = $xml.CreateElement("Description")
$xmlText = $xml.CreateTextNode("Mach1")
$xmlElt.AppendChild($xmlText)

$xml.FirstChild.AppendChild($xmlElt);

$xml.SelectSingleNode("//d:Database/d:Description", $ns) 

$xml.Save("test.xml")

This is the xmla (top portion):

<Batch Transaction="false" xmlns="http://schemas.microsoft.com/analysisservices/2003/engine">
  <Alter AllowCreate="true" ObjectExpansion="ExpandFull">
    <Object>
      <DatabaseID>CRH_TA1</DatabaseID>
    </Object>
    <ObjectDefinition>
      <Database xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ddl2="http://schemas.microsoft.com/analysisservices/2003/engine/2" xmlns:ddl2_2="http://schemas.microsoft.com/analysisservices/2003/engine/2/2" xmlns:ddl100_100="http://schemas.microsoft.com/analysisservices/2008/engine/100/100" xmlns:ddl200="http://schemas.microsoft.com/analysisservices/2010/engine/200" xmlns:ddl200_200="http://schemas.microsoft.com/analysisservices/2010/engine/200/200" xmlns:ddl300="http://schemas.microsoft.com/analysisservices/2011/engine/300" xmlns:ddl300_300="http://schemas.microsoft.com/analysisservices/2011/engine/300/300" xmlns:ddl400="http://schemas.microsoft.com/analysisservices/2012/engine/400" xmlns:ddl400_400="http://schemas.microsoft.com/analysisservices/2012/engine/400/400">
        <ID>CRH_TA1</ID>
        <Name>CRH_TA1</Name>
        <DataSourceImpersonationInfo>
          <ImpersonationMode>ImpersonateAccount</ImpersonationMode>
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
dirtyw0lf
  • 1,899
  • 5
  • 35
  • 63

1 Answers1

2
$xml.FirstChild.AppendChild($xmlElt);

Your code appends the newly created element to the first child node of the XML document. In your case that seems to be the document root element. And it only works because your XML file apparently doesn't contain a declaration (<?xml ...?>), otherwise you'd be getting an error.

You need to actually select the node to which you want to append the new element, and then call AppendChild() on that node.

$parent = $xml.SelectSingleNode('//d:Batch/d:Alter/d:Object', $ns)
$parent.AppendChild($xmlElt)
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328