Inserting xml nodes

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 5 years, 8 months ago.

  • Author
    Posts
  • #5834

    by Ritmo2k at 2013-04-22 08:36:23

    I have some xml I parse out and need to insert a default node into if it does not already exist:

    [XML]$xml = Get-Content 'C:\path\file.xml'

    $def_node = Select-Xml -Xml $xml -XPath "/root/def_node"
    $def_node_xml = $def_node.get_Node()

    Foreach ($element in (Select-Xml -Xml $xml -XPath $query))
    {
    $foo_xml = $element.get_Node()
    Try
    {
    $foo_xml.test_node
    }
    Catch
    {
    # Insert $def_node_xml into an element named 'test_node'.
    }

    I am not clear on how to go about this, I assumed I had to CreateElement on $foo_xml then AppendChild($def_node_xml) on it but that doesnt work.
    Any ideas?

    Thanks!

    by Ritmo2k at 2013-04-22 17:53:10

    Solved this, you can still manipulate the System.Xml.XmlNode object ($xml ) while in the foreach loop where $query_new
    is a derived query applicable to the current $element you are iterating over.

    $xml.SelectSingleNode($query_new).AppendChild($def_node_xml)

You must be logged in to reply to this topic.