Powershell XML 添加子元素

永远卡住

想要在 system.web 元素中添加另一个子元素。到目前为止,我已经尝试了多种方法,但是都没有奏效。我已经创建了这段代码,我不确定它是否接近。

到目前为止的代码:

#setting variables
$path = "H:\PSTesting\Logs\ExerciseXml.xml"
$xml = Get-Content $path

#Creating element
$child = $xml.CreateElement("Test")

#setting attributes
$child.SetAttribute('Testing','hey = "something"')

#adding attributes to the location
$xml.'system.web'.AppendChild($child)

#save file
$xml.Save($path)

下面是我需要更改的 XML。当前的:

<?xml version="1.0" encoding="UTF-8"?>
-<configuration>
    -<system.web>
        <authentication mode="None"/>
        <compilation targetFramework="4.5.1" debug="false"/>
        <httpRuntime targetFramework="4.5.1"/>
    </system.web>
</configuration>

以下是运行代码的预期结果。

<?xml version="1.0" encoding="UTF-8"?>
-<configuration>
    -<system.web>
        <authentication mode="None"/>
        <compilation targetFramework="4.5.1" debug="false"/>
        <httpRuntime targetFramework="4.5.1"/>
        <Testing Hey = 'something'>
    </system.web>
</configuration>

任何帮助,将不胜感激。提前致谢!

罗伯特·迪亚斯

你很接近,只是一些变化:

#setting variables
$path = "H:\PSTesting\Logs\ExerciseXml.xml"
[xml]$xml = Get-Content $path

#Creating element
$child = $xml.CreateElement("Testing")

#setting attributes
$child.SetAttribute('hey','something')

#adding attributes to the location
$xml.configuration.'system.web'.AppendChild($child)

#save file
$xml.Save($path)

顺便说一句,您可能希望-从您的示例中删除,因为它们具有误导性(xml实际上并不包含它们,并且它们仅在从 IE 等程序打开时才可见)

编辑:正如Rohin Sidharth所提到的,作为最佳实践,最好指定类型(尽管只要文件格式正确,PowerShell 就会自动检测它)。

Edit2:澄清什么是错的:

$child = $xml.CreateElement("Test")

这将根据您想要的输出创建Test您想要Testing命名元素

$child.SetAttribute('Testing','hey = "something"')

这将创建Testing具有值的属性hey = "something"

$xml.'system.web'.AppendChild($child)

这将不起作用,因为正确的路径是$xml.configuration.'system.web'而不是$xml.'system.web'.

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章