Add New value to XML via powershell

4d554d424c4553

I have Googled how to do this and I am struggling to understand. I currently have this XML

<?xml version="1.0" encoding="utf-8"?>
<gl:GLOBALLISTS Xmlns:gl="http://schemas.microsoft.com/VisualStudio/2005/workitemtracking/globallists">
<GLOBALLIST name="ListOfVersions - PWCC">
<LISTITEM value="1.1.3.2705" />
<LISTITEM value="1.1.4.2801" />
<LISTITEM value="1.1.4.2802" />
<LISTITEM value="1.1.4.2803" />
<LISTITEM value="1.1.4.2804" />
<LISTITEM value="1.1.5.2901" />
<LISTITEM value="1.1.5.2902" />
<LISTITEM value="Unknown" />
</GLOBALLIST>
</gl:GLOBALLISTS>

In a C:\ drive location. I want to use PowerShell to add a new list item value using a $NewListItem. So I can specify this each time I need to. So the List would now include 1.1.5.2903 as an example.I have tried using other code provided on other site but to no luck.

Any help would be much appricated

Duncan

Here's how to do it (but you'll need to change your input to be valid XML, 'xmlns' has to be lowercase).

PS C:\temp> cat t.xml
<?xml version="1.0" encoding="utf-8"?>
<gl:GLOBALLISTS xmlns:gl="http://schemas.microsoft.com/VisualStudio/2005/workitemtracking/globallists">
<GLOBALLIST name="ListOfVersions - PWCC">
<LISTITEM value="1.1.3.2705" />
<LISTITEM value="1.1.4.2801" />
<LISTITEM value="1.1.4.2802" />
<LISTITEM value="1.1.4.2803" />
<LISTITEM value="1.1.4.2804" />
<LISTITEM value="1.1.5.2901" />
<LISTITEM value="1.1.5.2902" />
<LISTITEM value="Unknown" />
</GLOBALLIST>
</gl:GLOBALLISTS>
PS C:\temp> [xml]$data = [xml](get-content c:\temp\t.xml)
PS C:\temp> $item = $data.CreateElement('LISTITEM')
PS C:\temp> $item.SetAttribute('value', "1.1.5.2903")
PS C:\temp> [void]$data.GLOBALLISTS.GLOBALLIST.appendChild($item)
PS C:\temp> $data.save('c:\temp\t2.xml')
PS C:\temp> cat t2.xml
<?xml version="1.0" encoding="utf-8"?>
<gl:GLOBALLISTS xmlns:gl="http://schemas.microsoft.com/VisualStudio/2005/workitemtracking/globallists">
  <GLOBALLIST name="ListOfVersions - PWCC">
    <LISTITEM value="1.1.3.2705" />
    <LISTITEM value="1.1.4.2801" />
    <LISTITEM value="1.1.4.2802" />
    <LISTITEM value="1.1.4.2803" />
    <LISTITEM value="1.1.4.2804" />
    <LISTITEM value="1.1.5.2901" />
    <LISTITEM value="1.1.5.2902" />
    <LISTITEM value="Unknown" />
    <LISTITEM value="1.1.5.2903" />
  </GLOBALLIST>
</gl:GLOBALLISTS>

If you have multiple GLOBALLIST items you'll need to select the appropriate one using XPath:

$node = $data.SelectSingleNode("//GLOBALLIST[@name='ListOfVersions - PWCC']")
$node.appendChild($item)

Or you can match part of the attribute:

$node = $data.SelectSingleNode("//GLOBALLIST[contains(@name, 'ListOfVersions']")

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related