0

I've been working on this all day and can't seem to adapt an answer for a .NET based solution or native powershell solution to fit my needs.

Here's essentially my problem. I have a few various sets of XML nodes and their children like so:

[xml]$parentContainer = @"
<?xml version="1.0"?>
<parentcontainer></parentcontainer>
"@

[xml]$parent = @"
<parent>
  <attribute>someattribute</attribute>
  <childcontainer></childcontainer>
</parent>
"@

[xml]$child = @"
<child>
  <childattr>something</childattr>
  <boolval>yes</boolval>
</child>
"@

Each of these pieces is returned by an associated class inside of PowerShell and my goal is to eventually combine them all into a single document. So it may look like this:

<?xml version="1.0"?>
<parentcontainer>
  <parent>
    <attribute>someattribute</attribute>
    <childcontainer>
      <child>
        <childattr>something</childattr>
        <boolval>yes</boolval>
      </child>
      <child>
        <childattr>something</childattr>
        <boolval>yes</boolval>
      </child>
    </childcontainer>
</parent>
</parentcontainer>

I've tried a handful of approaches including appending the child nodes as fragments, importing the nodes into a common document, using XDocument classes instead of XmlDocument classes but nothing quite gets me there. Some of my nodes are interpreted by PowerShell as strings so I can't use node based functions on them, the parent nodes are interpreted as documents instead of nodes so I lose the top layer when trying to append them, etc...

What's the best way of doing something like this either in PowerShell or .NET?

1 Answer 1

1

Try this:

[xml]$parentContainer = @"
<?xml version="1.0"?>
<parentcontainer></parentcontainer>
"@

[xml]$parent = @"
<parent>
  <attribute>someattribute</attribute>
  <childcontainer></childcontainer>
</parent>
"@

[xml]$child = @"
<child>
  <childattr>something</childattr>
  <boolval>yes</boolval>
</child>
"@

#Add Node child 1 to parent
$xpath = '//parent/childcontainer'
$childnode1 = $parent.SelectSingleNode($xpath)
$childnode1.AppendChild($parent.ImportNode(($child.child), $true));

#Add Node child 2 to parent
$childnode2 = $parent.SelectSingleNode($xpath)
$childnode2.AppendChild($parent.ImportNode(($child.child), $true));

#Add Node parent to parentcontainer
$xpath = '//parentcontainer'
$childnode = $parentContainer.SelectSingleNode($xpath)
$childnode.AppendChild($parentContainer.ImportNode(($parent.parent), $true));

#show result
$parentcontainer.InnerXml 
Sign up to request clarification or add additional context in comments.

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.