我想向现有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>
答案 0 :(得分:1)
您的XML数据使用名称空间,因此您需要注意这一点。 <core>
节点定义了适用于其所有子节点的默认名称空间(xmlns="urn:activemq:core"
)。创建一个名称空间管理器并将其添加到其中:
$nm = New-Object Xml.XmlNamespaceManager $xml.NameTable
$nm.AddNamespace('foo', 'urn:activemq:core')
选择要将新节点附加到的节点:
$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)