[英]Xml parsing in powershell:Adding and removing
我正在尝试使用 powershell 从 xml 文件中添加和删除条目。 这就是我的 xml 文件内容的样子。
<?xml version="1.0" encoding="UTF-8"?>
<jdbc-data-source>
<name>namevalue</name>
<jdbc-driver-params>
<url>connval</url>
<driver-name>DriverVal</driver-name>
<properties>
<property>
<name>user</name>
<value>username</value>
</property>
</properties>
<password-encrypted>encryptedpwd</password-encrypted>
</jdbc-driver-params>
</jdbc-data-source>
我需要删除 encryptedpwd 条目并添加 unencryptedpwd
我一直在尝试使用以下代码。
$file = "Path of xml file with content as mentioned above"
Get-ChildItem $file | % {
[Xml]$xml = Get-Content $_.FullName
$addItem = $xml.CreateElement('password')
$addItem.PsBase.InnerText = 'unencryptedpwd'
$xml.'jdbc-data-source'.'jdbc-driver-params'.AppendChild($addItem) | Out-Null
$nodes = $xml.'jdbc-data-source'.'jdbc-driver-params'
$nodes | % {
$child_node = $_.SelectSingleNode('password-encrypted')
$_.RemoveChild($child_node) | Out-Null
}
$xml.OuterXml | Out-File $_.FullName
}
它有以下问题。
它不会删除子“密码加密”。
它删除所有换行符。
请问有人可以帮忙吗?
首先,您的示例 xml 格式不正确 - 根元素需要正确关闭:底部<jdbc-data-source>
应该是</jdbc-data-source>
。
假设这是固定的,您需要使用 xml 解析器解析 xml,并使用 xpath 来定位、删除和插入您的元素。
所以,如果我理解你的正确,这应该有效:
$xml=[Xml]@"
[your xml above, fixed]
"@
$newpass=@'
<password>unencryptedpwd</password>
'@
#locate the element to delete
$node = $xml.SelectSingleNode('//password-encrypted')
#go to its parent and delete the child
$dest = $node.ParentNode
$dest.RemoveChild($node)
#import the new element as a fragment
$xmlFragment=$xml.CreateDocumentFragment()
$xmlFragment.InnerXML=$newpass
#finally, insert it in the xml
$dest.AppendChild($xmlFragment)
修改后的 xml 应如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<jdbc-data-source>
<name>namevalue</name>
<jdbc-driver-params>
<url>connval</url>
<driver-name>DriverVal</driver-name>
<properties>
<property>
<name>user</name>
<value>username</value>
</property>
</properties>
<password>unencryptedpwd</password>
</jdbc-driver-params>
</jdbc-data-source>
另一种但类似的方法如下:
[xml]$xml = @'
<?xml version="1.0" encoding="UTF-8"?>
<jdbc-data-source>
<name>namevalue</name>
<jdbc-driver-params>
<url>connval</url>
<driver-name>DriverVal</driver-name>
<properties>
<property>
<name>user</name>
<value>username</value>
</property>
</properties>
<password-encrypted>encryptedpwd</password-encrypted>
</jdbc-driver-params>
</jdbc-data-source>
'@
# remove the 'password-encrypted' node
$node = $xml.SelectSingleNode('//password-encrypted')
[void]$node.ParentNode.RemoveChild($node)
# create and add the new 'unencryptedpwd' node
$newNode = $xml.CreateElement('unencryptedpwd')
$newNode.InnerText = 'your unencrypted password'
[void]$xml.'jdbc-data-source'.'jdbc-driver-params'.AppendChild($newNode)
$xml.Save('D:\Test\test.xml')
PS 加载 xml 比使用自动考虑文档编码的Get-Content
更好的方法:
# load the xml file. This way, you are ensured to get the file encoding correct
$xml = [System.Xml.XmlDocument]::new()
$xml.Load($_.FullName)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.