使用 PowerShell 将新节点插入 XML [英] Inserting a new node into XML with PowerShell
问题描述
我有一个 XML 模式,我正在尝试将新节点插入其中:
I have an XML schema that I'm trying to insert new nodes into:
<clusters>
<cluster>
<name>
cfcluster
</name>
<port>
45564
</port>
<sessionreplication>
true
</sessionreplication>
<server>
cfusion1
</server>
<server>
cfusion2
</server>
<stickysession>
true
</stickysession>
</cluster>
</clusters>
我正在尝试编写一个具有新 sever 值的脚本,将根据现有值对其进行检查,如果找不到,则在现有值之后插入新值.比如说我有一个新的服务器值 cfusion3,我希望我的新输出像这样结束:
I'm trying to write a script that has a new sever value, will check it against existing ones, then insert the new one after existing ones if it isn't found. Say for example I have a new server value cfusion3, I'd want my new output to end up like this:
<clusters>
<cluster>
<name>
cfcluster
</name>
<port>
45564
</port>
<sessionreplication>
true
</sessionreplication>
<server>
cfusion1
</server>
<server>
cfusion2
</server>
<server>
cfusion3
</server>
<stickysession>
true
</stickysession>
</cluster>
</clusters>
假设我将 xml 存储在 $clusterData 中并且我要插入的新服务器存储在 $cfInstance.name 中,我想我会使用这样的东西,但无法让它工作......
Assuming I have the xml stored in $clusterData and the new server I want to insert is stored in $cfInstance.name, I was thinking I'd use something like this, but can't get it working...
if (-not ($clusterData.clusters.cluster.server -match $cfInstance.name)) {
$oldServer = ($clusterData | Select-Xml '/clusters/cluster/server').get_node()
$newServer = $clusterData.CreateElement("server")
$newServer.InnerText = $cfInstance.name
$clusterData.InsertAfter($newServer, $oldServer)
}
我很确定问题在于 $oldServer
正在获取所有 <server>
节点,但我不确定如何修改 xpath
得到一个.我试过:
Select-Xml -Xml $clusterData -XPath "clusters/cluster/server[text()='cfusion2']"
但这不会返回任何内容.有什么建议吗?
I'm pretty sure the problem is that $oldServer
is getting all <server>
nodes and I'm not sure how to modify the xpath
to get just one. I've tried:
Select-Xml -Xml $clusterData -XPath "clusters/cluster/server[text()='cfusion2']"
but that doesn't return anything. Any suggestions?
推荐答案
使用以下 XPath 返回仅最后一个现有的 server
元素:
Use the following XPath to return only the last existing server
element :
/clusters/cluster/server[last()]
/clusters/cluster/server[text()='cfusion2']
可能不起作用,因为相应 server
元素的内部文本不完全正确等于 "cfusion2"
.有您没有考虑的空白.在进行比较之前尝试使用 normalize-space()
清理不必要的空格,如下所示:
/clusters/cluster/server[text()='cfusion2']
didn't work possibly because the inner text of the corresponding server
element isn't exactly equals to "cfusion2"
. There are white-spaces that you didn't consider. Try using normalize-space()
to clean up unnecessary white-spaces before doing comparison, like so :
/clusters/cluster/server[normalize-space()='cfusion2']
这篇关于使用 PowerShell 将新节点插入 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!