Add Element to XML

天大地大妈咪最大 提交于 2019-12-31 05:37:17

问题


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 added with my code.

The XML:

<?xml version="1.0"?>
<configuration xmlns="urn:activemq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xi="http://www.w3.org/2001/XInclude" xsi:schemaLocation="urn:activemq /schema/artemis-configuration.xsd">
  <core xmlns="urn:activemq:core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:activemq:core ">
    <connectors>
      <!-- Connector used to be announced through cluster connections and notifications -->
      <connector name="artemis">tcp://xxxxxxx:61616</connector>
      <connector name="blaat" xmlns="" />
    </connectors>
  </core>
</configuration>
[xml]$xml = Get-Content d:\data\test-broker\etc\broker.xml

$xml.configuration.core.connectors.connector.ChildNodes.Item(0).value

$Node = $xml.CreateElement("connector");
$Node.SetAttribute("name", "blaat");
$xml.configuration.core.connectors.AppendChild($node)
$xml.configuration.core.connectors.connector.SetValue("tcp://");
$xml.Save("d:\data\test-broker\etc\broker.xml")

I want the XML to be like this:

<?xml version="1.0"?>
<configuration xmlns="urn:activemq" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xi="http://www.w3.org/2001/XInclude" xsi:schemaLocation="urn:activemq /schema/artemis-configuration.xsd">
  <core xmlns="urn:activemq:core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:activemq:core ">
    <connectors>
      <!-- Connector used to be announced through cluster connections and notifications -->
      <connector name="artemis">tcp://xxxx1:61616</connector>
      <connector name="blaat">tcp://xxxxx2:61616</connector>
    </connectors>
  </core>
</configuration>

回答1:


Your XML data uses namespaces, so you need to take care of that. The <core> 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)


来源:https://stackoverflow.com/questions/56355321/add-element-to-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!