views:

98

answers:

2

Hi, Im trying to construct a powershell script that uses some XML. I have a XML document where I try to add some values with email addresses. The finished xml document should have this format: (I'm only showing the relevant part of the xml here)

<emailAddresses> 
    <value>[email protected]</value> 
    <value>[email protected]</value> 
    <value>[email protected]</value> 
</emailAddresses>

SO, in powershell I try to do this as a test, which fails:

$newNumber = [xml] '<value>555-1215</value>'
$newNode = $Request2.ImportNode($newNumber.value, $true)
$emailnode.AppendChild($newNode)

After some reading, I have figured out that if I do this, it suceeds:

$newNumber = [xml] '<value name="flubber">555-1215</value>'
$newNode = $Request2.ImportNode($newNumber.value, $true)
$emailnode.AppendChild($newNode)

So, I am stuck. I'm starting to wonder if I should use another function instead of importnode when I have several keys with the same name but different values.

As you guys probably have figured out by now, i'm not an expert in xml. ANy help appreciated!

+2  A: 

As you've indicated, there are pieces of XML that have been left out of the question so I've constructed my own rendition that hopefully adapts to the real world version.

First off...

$newNumber.value

... is of type string. ImportNode() expects a XmlNode type as the first parameter. To get this, you can probably call a function like get_DocumentElement() and/or SelectSingleNode().

For example:

$Request2 = [xml]'<root><emailAddresses/></root>'
$newNumber = [xml]'<value>555-1215</value>'
$newNode = $Request2.ImportNode( $newNumber.get_DocumentElement(), $true )
$Request2.get_DocumentElement().SelectSingleNode( './emailAddresses' ).AppendChild( $newNode )

This should render the results that you're looking for.

Scott Saad
A: 

Try this approach:

PS> $xml = [xml]'<addresses/>'
PS> $newNode = $xml.CreateElement('value')
PS> $newNode.InnerText = '[email protected]'
PS> $xml.DocumentElement.AppendChild($newNode) > $null
PS> $newNode = $xml.CreateElement('value')
PS> $newNode.InnerText = '[email protected]'
PS> $xml.DocumentElement.AppendChild($newNode) > $null
PS> $xml.DocumentElement.OuterXml
<addresses><value>[email protected]</value><value>[email protected]</value></addresses>