PowerShell - 从现有 XML 节点同级创建变量
首先,我要提一下,我是 PowerShell 的初学者,想提前感谢大家的帮助。
我在 PowerShell 脚本中有一个函数,可以使用它创建许多新的 XML 节点。
$fileElement = $xml.CreateElement("FileRef")
$fileElement.SetAttribute("Id",$refId)
这工作得很好,所以我有几个名为 FileRef 的节点同级节点,每个都有不同的 Id 属性。稍后在脚本中再次使用 $fileElement 变量,使用 $fileElement.AppendChild 添加自己的子节点。
我现在遇到的情况是,我有一个循环多次调用脚本函数并传入相同的 $refId 变量。我遇到的问题是输出得到具有相同 id 的重复 FileRef 节点同级。
在某些情况下,我想做的是从现有的 FileRef 节点兄弟节点创建 $fileElement 变量,其 id = $refId (以便我稍后仍可以在脚本中对变量使用 AppendChild),而不是创建id = $refId 的新 XML 节点同级(这导致了重复)。例如
if(circumstances)
{
# first call to the function in the loop, so create new node sibling
$fileElement = $xml.CreateElement("FileRef")
$fileElement.SetAttribute("Id",$refId)
}
else
{
# node sibling already exists, do not create new node,
# use existing node sibling with id = $refId
create xml node variable $fileElement here
}
谢谢
First off, let me mention that I am a beginner at PowerShell and would like to thank everyone for their help in advance
I have a function in a PowerShell script that creates numerous new XML nodes using
$fileElement = $xml.CreateElement("FileRef")
$fileElement.SetAttribute("Id",$refId)
This works fine so I have several node siblings called FileRef, each with different Id attributes. The $fileElement variable gets used again later on in the script where it gets it's own child nodes added, using $fileElement.AppendChild.
I now have circumstances where I have a loop that calls the script function multiple times passing in the same $refId variable. The problem I have is that the output is getting duplicated FileRef node siblings with the same id.
What I would like to do, under certain circumstances, is create the $fileElement variable from an existing FileRef node sibling with the id = $refId (so that I can still use AppendChild on the variable later on in the script) instead of create a new XML node sibling with the id = $refId (which is causing the duplication). E.g.
if(circumstances)
{
# first call to the function in the loop, so create new node sibling
$fileElement = $xml.CreateElement("FileRef")
$fileElement.SetAttribute("Id",$refId)
}
else
{
# node sibling already exists, do not create new node,
# use existing node sibling with id = $refId
create xml node variable $fileElement here
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,我已经设法使用以下 PowerShell 代码解决了我的问题:
当我需要查找现有的兄弟节点时,我获取我正在查找的类型的第一个节点,并根据传入的 $refId 检查它的 Id 属性。如果它们不匹配,我将查看下一个兄弟,依此类推,直到 2 个 id 匹配。
虽然这可能不是实现我的目标的最优雅的方式,但它确实有效:-)
Ok, I've managed to solve my problem with the following PowerShell code:
When I need to find an existing node sibling, I get the first node of the type I'm looking for and check it's Id attribute against the passed in $refId. If they do not match, I will look at the next sibling and so on until the 2 ids match.
While this may not be the most elegant way to achieve my goal, it does work nonetheless :-)