Add Xml string to an Xml Node

Viewed 43

I've been googling for a while now and I'm about to quit!

so I have an XML string:

$xmlPom = [xml]"<repositories>
<repository>
<id>Test-Org</id>
<url>https://pkgs.dev.azure.com/Test/_packaging/Test-Org/maven/v1</url>
<releases>
    <enabled>true</enabled>
</releases>
<snapshots>
    <enabled>true</enabled>
</snapshots>
</repository>
</repositories>"

and I want to add it to my an existing powershell file. The schema is as follows:

    <project>
  <modelVersion></modelVersion>
  <parent>
    <groupId></groupId>
    <artifactId></artifactId>
    <version></version>
    <relativePath />
  </parent>
  </project>

What I want to do it take the string above and inject it under <project>. This is the code I currently have:

$xdoc = new-object System.Xml.XmlDocument
$fileXml = resolve-path(“$dest\test.xml”)
$xdoc.load($fileXml)
$xdoc.project.AppendChild($xmlPom)

When I run this, I get the following error:

Exception calling "AppendChild" with "1" argument(s): "The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type."
At line:47 char:1
+ $xdoc.project.AppendChild($xmlPom)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Any ideas?

1 Answers

Just as I hit the submit button, I figured it out!

I just had to import the node:

$xdoc.project.AppendChild($xdoc.ImportNode($xmlPom.repositories, $true))
Related