Sergio Lara
Sergio Lara

Reputation: 35

Import node to another XML document

This is what i have so far but i get a "The node to be inserted is from a different document context." Error. Any ideas?

$xml = [xml](Get-Content "C:\IT\HowardCo\Compare\New.xml") 
$xmld = [xml](Get-Content "C:\IT\HowardCo\Compare\ConfigExport.xml") 
$newNode = $xml.ImportNode($xmld.SelectSingleNode("//SaleItem[SaleItemId=2]"), $true)
$xmld.DocumentElement.AppendChild($newnode)
$xml.Save("C:\IT\HowardCo\Compare\New.xml") 

This is the XML that im trying to grab info from. Its a list of Items organized by SaleItemID Im trying to grab the item and the Price1 under RevenueCenter. Any Help with this would be amazing.

<ConfigExport>
    <SaleItems>
        <SaleItem>
            <SaleItemId>2</SaleItemId>
            <AltItemId>0</AltItemId>
            <Description>*Torta Ahogada Combo</Description>
            <Description2/>
            <Division>2</Division>
            <Available>1</Available>
            <BarCode/>
            <Plu Id="0"/>
            <Function Id="0">Revenue</Function>
            <RevenueCenter Id="1" Name="La Cocina">
                <Price1>6.49</Price1>
                <Price2>6.49</Price2>
                <ItemAvailabilityByMode>
                    <Mode Id="1" Name="Here">
                        <Available>1</Available>
                    </Mode>
                    <Mode Id="2" Name="To Go">
                        <Available>1</Available>
                    </Mode>
                </ItemAvailabilityByMode>
            </RevenueCenter>
        </SaleItem>
    </SaleItems>
</ConfigExport>

Upvotes: 3

Views: 5094

Answers (1)

Matthew Wetmore
Matthew Wetmore

Reputation: 988

Assuming your new.xml starts out something like this:

<ConfigExport>
    <SaleItems>
    </SaleItems>
</ConfigExport>

You seem to appending the node back into the same document you read it from in the first place with the next to last line - I assume that's not what you intended. Ambiguously defined variable names makes the code hard to read and debug.

Here's a simple re-write with clearer naming:

$importXml = [xml]( Get-Content "C:\IT\HowardCo\Compare\New.xml" )
$exportXml = [xml]( Get-Content "C:\IT\HowardCo\Compare\ConfigExport.xml" ) 
$node = $exportXml.SelectSingleNode( "//SaleItem[SaleItemId=2]" )
$newNode = $importXml.ImportNode($node, $true)
$importXml.DocumentElement.AppendChild($newnode)
$importXml.Save( "C:\IT\HowardCo\Compare\New.xml" ) 

In your original code, with naming like this, you might have more quickly seen that you were appending the $newNode into $exportXml.

Upvotes: 3

Related Questions