【问题标题】:Add Element to XML将元素添加到 XML
【发布时间】:2019-10-14 18:09:05
【问题描述】:

我想向现有 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 powershell powershell-4.0


    【解决方案1】:

    您的 XML 数据使用命名空间,因此您需要注意这一点。 &lt;core&gt; 节点定义了适用于其所有子节点的默认命名空间 (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)
    

    【讨论】:

      猜你喜欢
      • 2012-04-14
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      相关资源
      最近更新 更多