Home > Software design >  XML Powershell get and remove element node
XML Powershell get and remove element node

Time:11-05

I want to remove one element from MsDtsSrvr.ini, namely this whole node:

<Folder xsi:type="SqlServerFolder">
      <Name>MSDB</Name>
      <ServerName>.</ServerName>
    </Folder>

File looks like this:

<?xml version="1.0" encoding="utf-8"?>
<DtsServiceConfiguration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <StopExecutingPackagesOnShutdown>true</StopExecutingPackagesOnShutdown>
  <TopLevelFolders>
    <Folder xsi:type="SqlServerFolder">
      <Name>MSDB</Name>
      <ServerName>.</ServerName>
    </Folder>
    <Folder xsi:type="FileSystemFolder">
      <Name>File System</Name>
      <StorePath>..\Packages</StorePath>
    </Folder>
  </TopLevelFolders>
</DtsServiceConfiguration>

What I am failing to do is to get this whole node into variable, unless I do something like:

$sqlserverFolder = $xmlFile.SelectSingleNode("/DtsServiceConfiguration/TopLevelFolders/Folder")
$sqlServerFolder.ParentNode.RemoveChild($sqlServerFolder)

This achieves what I want, however obvious problem with that is I am not selecting this particualar node, I suppose powershell is just selecting first one. Which I'd prefer to avoid to understand what's going on really.

When I select all nodes using this script:

$xmlFile.SelectNodes("/DtsServiceConfiguration/TopLevelFolders/Folder")

I get following results:

type             Name        ServerName
----             ----        ----------
SqlServerFolder  MSDB        .         
FileSystemFolder File System     

So I tried to run something like this:

$xmlFile.SelectNodes("/DtsServiceConfiguration/TopLevelFolders/Folder[@type='SqlServerFolder']")

but it does not return any results. How can I grab this particular node so I can remove it?

CodePudding user response:

Use the local-name() XPath function to filter on the xsi:type attribute by it's local name (type):

$xmlFile.SelectSingleNode("/DtsServiceConfiguration/TopLevelFolders/Folder[@*[local-name()='type' and . ='SqlServerFolder']]")
  • Related