0

i have a problem adding values to an xml array property. The xml looks like this:

$xml = [xml]@"
<letters>
    <letter><to>mail a</to></letter>
    <letter>
        <to>mail a</to>
        <to>mail b</to>
    </letter>
</letters>
"@

$letter = $xml.letters.letter[1]
$letter.to
#mail a
#mail b

now i want to add items ("mail c", "mail d") to the "to" array:

$letter.to
#mail a
#mail b
#mail c
#mail d

But i don't seem to be able to.

a) simply trying to set anything to the property results in a misleading error:

$letter.to += "a"
#"to" kann nicht festgelegt werden, da nur Zeichenfolgen als Werte zum Festlegen von XmlNode-Eigenschaften verwendet werden können.
#Bei Zeile:1 Zeichen:9
#+ $letter. <<<< to += "a"
#    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
#    + FullyQualifiedErrorId : PropertyAssignmentException

But that probably boils down to "to" not having a setter:

$letter | Get-Member
#Name       MemberType      Definition
#[bunch of stuff]
#to         Property        System.Object[] {get;}

b) Setting a value via SetAttribute partly works, but results in unusable (and very strange) behaviour:

$letter.SetAttribute("to", "mail c")
$letter.to
#mail c     <- why is it up front?
#mail a
#mail b

$letter.SetAttribute("to", "mail d")
$letter.to
#mail d     <- why is mail c gone?
#mail a
#mail b 

Does anyone have an Idea what to try next?

2 Answers 2

2

Basically, you want to create a new XmlElement, set the InnerText value, and append it to the parent <letter> element :

$to = $xml.CreateElement("to")
$to.InnerText = "mail c"
$letter.AppendChild($to)
$letter.to

Output :

mail a
mail b
mail c

Similar example can be found in the MSDN documentation of XmlNode.AppendChild().

Sign up to request clarification or add additional context in comments.

Comments

1

This will do the trick, you can create a fragment and add the innerxml for the to tag (since it's unstructured):

$letter = $xml.letters.letter[1]
$to= $xml.CreateDocumentFragment();
# Create the to node
$to.InnerXml = "<to>mail c</to>"
$letter.AppendChild($to);
# show the node
$letter

Altarnatively you could create the to tag on the document with the following:

$to = $xml.CreateElement("to")

Then set it's property (inner text) :

$to.InnerText = "mail c"

And append the item with

$letter.AppendChild($to)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.