Add Element to XML

后端 未结 1 1880
囚心锁ツ
囚心锁ツ 2021-01-26 01:13

I want to add a element (connector) to a existing XML, this was succesfull but I need to remove the xmlns= and want to add an value to it. The connector blaat is ad

1条回答
  •  迷失自我
    2021-01-26 01:23

    Your XML data uses namespaces, so you need to take care of that. The node defines a default namespace (xmlns="urn:activemq:core") that applies to all of its child nodes. Create a namespace manager and add that namespace to it:

    $nm = New-Object Xml.XmlNamespaceManager $xml.NameTable
    $nm.AddNamespace('foo', 'urn:activemq:core')
    

    Select the node to which you want to append your new node:

    $cn = $xml.SelectSingleNode('//foo:connectors', $nm)
    

    When creating the new node specify its default namespace, then set the node's attribute(s) and value:

    $node = $xml.CreateElement('connector', $cn.NamespaceURI)
    $node.SetAttribute('name', 'blaat')
    $node.InnerText = 'tcp://xxxxx2:61616'
    

    Now you can append the new node to the intended parent without getting a spurious xmlns attribute:

    [void]$cn.AppendChild($node)
    

    0 讨论(0)
提交回复
热议问题