xmlpowershellattributesnodesparent-node

XML Parent node modification using childnode attribute in Powershell


I'm trying to modify the Parent node attributes using the child node attributes in Powershell. What is the best way to do this? Any pointers are really appreciated. Below is the code. The name of the file is pricefile.xml

 <model type="model1" name="default" price="12.12" date="some_value">
  <PriceData>
    <item name="watch" price="24.28" date="2013-12-01"/>
    <item name="toy" price="22.34" date="2013-12-02"/>
    <item name="bread" price="24.12" date="2013-12-03"/>
  </PriceData>
 </model>

I would like to filter the above xml file using the name of the item. For example if I need the details of the item watch, I should be able to parse the above xml in powershell and get the following.

 <model type="model1" name="watch" price="24.28" date="2013-12-01">
  <PriceData>
    <item name="watch" />
  </PriceData>
 </model>

Notice how the attributes of the child node are removed and the model attributes have been reset with the watch attributes. Can you let me know the best way to do this.

If I use any of the below commands I get no output.

    [xml]$item = get-content pricefile.xml

    $item.SelectNodes("//item/@*").parentnode

    $item.SelectNodes("//item/@*") | where {$_.parentnode}

Solution

  • A very elegant solution has been provided in a similar question for parsing/traversing the xml document. It works well with traversing the tree in this question as well. Following is the link to the other question:

    Modify XML Parent Attributes iterating through Child attributes using powershell