如何使用powershell更新xml文件中的节点类型元素

问题描述 投票:0回答:1

我有一个下面的 xml 文件示例。我想更新元素设置节点并将其更改为“NewSettings”(以粗体突出显示)。我尝试通过 powershell 使用不同的属性和方法来更改它,但是它不起作用。

<configuration>
  **<Settings>**
    <test.Settings>
Some text block
    </test.Settings>
  **</Settings>**
</configuration>

到目前为止,我已经尝试过下面的方法和其他一些 powershell 方法来更改元素,但它不起作用

$path             = 'C:\temp1\web6.config'

$Newsetting        = 'NewSettings'

$xml = [xml](Get-Content $path)

$newxml = $xml.SelectSingleNode("//Settings")

$newxml.InnerText = $Newsetting

$xml.Save($path)
xml powershell
1个回答
0
投票

请参阅:如何使用 PowerShell 更新 XML 节点的值?

InnerText
属性更改元素内的文本,而不是元素的名称。您需要创建一个具有所需名称的新元素,将属性和子元素从旧元素克隆到新元素,替换并保存。

此脚本将用

<Settings>
元素替换
<NewSettings>
元素,保留所有属性和子元素。

$path = 'C:\temp1\web6.config'
$Newsetting = 'NewSettings'

# Load the XML file
$xml = xml

# Select the node to be renamed
$oldNode = $xml.SelectSingleNode("//Settings")

# Create a new node with the new name
$newNode = $xml.CreateElement($Newsetting)

# Clone attributes and children from the old node to the new node
foreach ($attribute in $oldNode.Attributes) {
    $newAttribute = $xml.CreateAttribute($attribute.Name)
    $newAttribute.Value = $attribute.Value
    $newNode.Attributes.Append($newAttribute)
}
foreach ($childNode in $oldNode.ChildNodes) {
    $newNode.AppendChild($childNode.Clone())
}

# Replace the old node with the new node in the parent
$oldNode.ParentNode.ReplaceChild($newNode, $oldNode)

# Save the XML document
$xml.Save($path)

尝试一下,如果有帮助请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.