简体   繁体   English

Powershell 脚本添加 XML 子元素

[英]Powershell script to add XML sub-elements

I'm getting crazy.我快疯了。 I need to modify this XML file in powershell我需要在 powershell 中修改这个 XML 文件

<Smart>
  <Settings>
    <Section name="x">
      <Parameter name="a" value="true" />
      <Parameter name="b" value="0" />
      <Parameter name="c" value="13873" />
      <Parameter name="d" value="true" />
      <Parameter name="e" value="EAI" />
    </Section>
    <Section name="z">
      <Parameter name="h" value="true" />
      <Parameter name="i" value="0" />
      <Parameter name="j" value="13873" />
      <Parameter name="k" value="true" />
      <Parameter name="l" value="EAI" />
    </Section>
  </Settings>
</Smart>

What I want to do is add another line such as:我想要做的是添加另一行,例如:

< Parameter name="f" value="OK" /> < 参数名称="f" 值="OK" />

But I want to add the new line inside the first Section < Section name="x">但我想在第一个 Section < Section name="x"> 中添加新行

    #Modify XML file
    Write-Host "OPENING XML FILE";
    $path = "\\$computer\$FileName"
    [xml] $xml = Get-Content $path
    
    #return $xml.SmartUpdate.Settings.Section.Parameter

    #set values for the XML nodes you need. This uses the XPath of the value needed.

   **WANT TO ADD THE NEW PARAMETER HERE**

    #Save the file
    $xml.save($path)
    Write-Host "XML FILE SAVED";

I cannot find the solution.我找不到解决方案。 Please help me请帮我

Something like this should work.像这样的东西应该工作。 Note that my XML skills with Powershell are far from good so I hope someone else has a better solution请注意,我的 XML 技能与 Powershell 远非好,所以我希望其他人有更好的解决方案

# Create a new node
$NewNode = $Xml.CreateNode([System.Xml.XmlNodeType]::Element,"Parameter",$null)
# create the attributes and set the values
$NameAttribute = $XMl.CreateAttribute('name')
$NameAttribute.Value = 'f'
$ValueAttribute = $Xml.CreateAttribute('value')
$ValueAttribute.Value = 'OK'
# append the attributes
$NewNode.Attributes.Append($NameAttribute)
$NewNode.Attributes.Append($ValueAttribute)
# append the new node to the correct parent
$Xml.Smart.Settings.Section.AppendChild($NewNode)

Since you have multiple Section nodes, you need to specify the node to append the new childnode to:由于您有多个Section节点,因此您需要将新的子节点指定为 append 到:


$path = "\\$computer\$FileName"
[xml]$xml = Get-Content -Path $path -Raw

# create a new childnode and append attributes to it
$childNode = $xml.CreateElement("Parameter")
$attrib = $xml.CreateAttribute('name')
$attrib.Value = 'f'
[void]$childNode.Attributes.Append($attrib)
$attrib = $xml.CreateAttribute('value')
$attrib.Value = 'OK'
[void]$childNode.Attributes.Append($attrib)

# select the parent node to append this childnode to
$parentNode = $xml.Smart.Settings.Section | Where-Object { $_.name -eq 'x' }
[void]$parentNode.AppendChild($childNode)

$xml.Save($path)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM