Adding child nodes to xml

by Apr 30, 2011

Hello everyone

I am exploring xml and am trying to write nested XML elements like this

<r>

   <c1>

      <c2></c2>

   </c1>

</r>

In other words, I was trying to write a root element with a child and sub child element. First I tried this:

[xml]$a = '<r></r>'

$b = $a.CreateElement("c1")

$a.r.AppendChild($b)

Method invocation failed because [System.String] doesn't contain a method named 'AppendChild'.

 

Secondly, I tried this:

[xml]$a = '<r></r>'

$b = $a.CreateElement("c1")

$a.DocumentElement.AppendChild($b)

$c = $a.CreateElement("c2")

$a.r.c1.AppendChild($c)

Method invocation failed because [System.String] doesn't contain a method named 'AppendChild'.

 

Whatever I try I can not create more than one child element. The child element is always created of type "system.string" instead of "System.Xml.XmlElement" or maybe "System.Xml.XmlNode". I have absolutly no idea to explain this behaviour. Does anyone know why this happens and is there a way to create an xml structure with "deeper" nesting than just a root/child element? (For example root/child/subchild/subsubchild etc.)

Thanks a lot for any help.

Thomas