繁体   English   中英

Powershell XML添加子元素

[英]Powershell XML Adding Child Element

想要在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>

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

我不相信Robdy的答案会起作用,因为它没有解决真正的问题,即Get-Content命令将xml读作文本文件。 因此,脚本中使用的xml属性和方法将不起作用。

但是,答案很简单:TypeCasting $xml[xml]

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

#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格式。

你很亲密,只有一些变化:

#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'

暂无
暂无

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

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