将元素添加到 XML

Add Element to XML

我想向现有的 XML 添加一个元素(连接器),这是成功的,但我需要删除 xmlns= 并想为其添加一个值。连接器 blaat 已添加到我的代码中。

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")

我希望 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://xxxx1:61616</connector>
      <connector name="blaat">tcp://xxxxx2:61616</connector>
    </connectors>
  </core>
</configuration>

您的 XML 数据使用命名空间,因此您需要注意这一点。 <core> 节点定义了一个应用于其所有子节点的默认名称空间 (xmlns="urn:activemq:core")。创建命名空间管理器并将该命名空间添加到其中:

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

Select 您要将新节点附加到的节点:

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

创建新节点时指定其默认名称空间,然后设置节点的属性和值:

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

现在您可以将新节点附加到预期的父节点,而不会获得虚假的 xmlns 属性:

[void]$cn.AppendChild($node)