Bankey Biharidassa
Bankey Biharidassa

Reputation: 37

Copy a value of an element into another element

I am trying to find out how I can get the value of <element1>value</element1> into <element16>value</element16> in the same XML.

<element16> has not a fixed position, but if it exist it needs to be filled with the value of <element1>.

I have to do it with PowerShell. Who can give me a hand?

This is what I have:

$latest = Get-ChildItem -Path $dir |
          Sort-Object LastAccessTime -Descending |
          Select-Object -First 1
$latest.Fullname

$attachment = $latest.Fullname

$xml = New-Object Xml
$xml.Load($latest.Fullname)

$xml.SelectSingleNode('/order/sf_st_mail').InnerText =
$xml.SelectSingleNode('/order/sf_re_mail').InnerText

$xml.Save($latest.Fullname)

This results in

Exception setting "#text": "The property '#text' cannot be found on this object"

Snipplet XML:

<order>
  <sf_re_mail>[email protected]</sf_re_mail>

  <element x, y ,z> </element x, y ,z>
  <sf_st_mail></sf_st_mail>
</order>

should become:

<order>
  <sf_re_mail>[email protected]</sf_re_mail>

  <element x, y ,z> </element x, y ,z>
  <sf_st_mail>[email protected]</sf_st_mail>
</order>

Upvotes: 0

Views: 285

Answers (1)

woxxom
woxxom

Reputation: 73806

Load the XML:

$xml = New-Object Xml
$xml.Load($latest)

Use XPath selectors in case the elements could be anywhere in the node tree:

$xml.SelectSingleNode('//sf_st_mail').InnerText =
     $xml.SelectSingleNode('//sf_re_mail').InnerText

Or access them directly if you know the tree structure:

$xml.order.sf_st_mail = $xml.order.sf_re_mail # for simple text values

To replace a complex node with nested sub-nodes:

$xml.someNode.parentNode.ReplaceChild($xml.anotherNode.Clone(), $xml.someNode)

Then save:

$xml.Save($latest)

Upvotes: 2

Related Questions