0
votes

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}
1
The best way to do this is to simply do this. Currently the question seems like a "do it for me" request. Have you tried something yourself? What was the problem? Can you add the code you've tried to the question? - wOxxOm
Updated with what I did. I given quite a few tries,which did not yield any results and hence did not add them as I wanted to know if there was a better way and did not want to mislead others or rather needed a fresher perspective, Thanks for being real helpful wOxxOm your comment really helps everyone who reads this question. - Jose
no need for the irony, you'd surprised by the amount of "gimme the codez" requests from clueless users on StackOverflow. Such questions aren't helpful to anyone. - wOxxOm
As for the task, $xml.SelectNodes('//item[@name="watch"]') selects the item nodes, then you can use .parentNode like you did. - wOxxOm
This is a pretty frequent problem and is more about traversing the xml tree using powershell rather than give me my exact code. By the way I've also spent hours searching for a similar question with no results, most of them have this problem solved for XLST or C# etc etc. Please check your facts before making generic comments. Thanks for your solution though, I'm trying to not really hardcode the attribute=value pair, I wanna get a genric way to find the parent based on only the attribute name, any attribute name, maybe I should update my question. - Jose

1 Answers

0
votes

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