Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import node to another XML document

Tags:

powershell

xml

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>
like image 626
Sergio Lara Avatar asked Sep 30 '26 12:09

Sergio Lara


1 Answers

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.

like image 199
Matthew Wetmore Avatar answered Oct 02 '26 08:10

Matthew Wetmore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!