Converting system.xml.xmlelement to system.xml.xmldocument using PowerShell

I am working on a historical script which I have limited.

Object A is of type system.xml.xmlelement

and I need to convert it to type system.xml.xmldocument

in order to perform comparison with Object B (type system.xml.xmldocument


The script is currently trying to do a direct conversion that it generates with:

Cannot convert value system.xml.xmlelement

to type system.xml.xmldocument

. Error: "The specified node cannot be inserted as a valid child of this node because the specified node is of the wrong type."

I feel like I need to create a new object system.xml.xmldocument

and import a node from object A into a new object and then do a comparison with the new object against object B. I'm afraid of the correct syntax, plus I'm not sure if this is the correct approach.

Any guidance or help would be appreciated.

Object A (xmlElement) looks like this:

<Resource xmlns="">
    <UsageMeters />
        <CacheServiceInput xmlns="" xmlns:xsd="" xmlns:xsi="">
            <Location>North Europe</Location>
            <Value>9/30/2014 9:46:42 AM +00:00</Value>
    <Label />


Object B (xmldocument) looks like this:

        <CacheServiceInput xmlns="" xmlns:xsi="" xmlns:xsd="">
            <Location>North Europe</Location>



source to share

1 answer

I know this is old, but as no one else answered, I thought I'd share this when faced with a similar issue. Basically, you cannot implicitly convert an XmlElement to an XmlDocument, but you can wrap it. The following syntax makes it easy:

Given the following dummy xml

<?xml version="1.0" encoding="utf-8"?>
 <configuration xmlns="http://dummy">


We could get a subset and convert it to a document like this:

$value = [xml](Get-Content(Join-Path $filePath $roles[0]))
$commonRoles = $value.configuration.CommonRoles
$xml = New-Object -TypeName xml
$xml.AppendChild($xml.ImportNode($commonRoles, $true)) | Out-Null


In this case, we read the xml source from the file and then select the nested element (CommonRoles), which becomes our XmlElement object. The subsequent lines will create a new xml object and add an XmlElement to this object. We need to use the ImportNode method as the xml is currently owned by another document, so you need to allow it to become part of the new document.

The pipe to Out-Null prevents the AppendChild from being called in the output of the function.



All Articles