PowerShell - create a variable from an existing XML node sibling
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
Ok, I've managed to solve my problem with the following PowerShell code:
if(circumstances)
{
$fileElement = $xml.CreateElement("fileRef")
$directoryRefElement.SetAttribute("Id",$refId)
}
else # use existing node
{
$fileElement = ""
$currentNode = $xml.get_Item("fileRef")
do
{
$currentId = $currentNode.GetAttribute("Id")
if ($currentId -eq $refId)
{
$fileElement = $currentNode
}
else
{
$tempNode = $currentNode
$currentNode = $tempNode.get_NextSibling()
}
}
while($fileElement -eq "")
}
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 :-)
精彩评论