Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I am new to PowerShell. I have to write a script which can return me the first parent(node) value by passing the child node.

I have the following XML. When I pass my PowerShell script the value "AAA", it should return "parent2", and when I pass "III", it should return "parent311".

Can someone help me write this script?

XML:

<root>
  <parent>
    <parent2>
      <child>AAA</child>
    </parent2>
    <parent3>
      <child>BBB</child>
      <child>CCC</child>
      <child>DDD</child>
    </parent3>
    <parent4>
      <child>EEE</child>
    </parent4>
    <parent5>
      <child>FFF</child>
    </parent5>
  </parent>
  <parent21>
    <parent211>
      <child>GGG</child>
    </parent211>
    <parent311>
      <child>HHH</child>
      <child>III</child>
      <child>JJJ</child>
    </parent311>
    <parent411>
      <child>KKK</child>
    </parent411>
    <parent511>
      <child>LLL</child>
    </parent511>
  </parent21>
</root>
share|improve this question
    
What have you tried? Where exactly are you getting stuck? –  Indrek Oct 24 '12 at 8:41
    
I am able to to display child tag details, I don't know how to get the parent tag details by giving the child value. And i am new to this powershell. If there is a option to reslove this please let me know. –  kumar Oct 24 '12 at 9:07

1 Answer 1

If you have a reference to the child node, you can get its parent node using the appropriately named ParentNode property. For instance, with the XML file you posted:

$xml = [xml](Get-Content file.xml)
$child = $xml.SelectSingleNode("root/parent/parent2/child")
$child.ParentNode.Name

Of course, you probably use some other method to get the child node than SelectSingleNode(), but it serves to illustrate the example. The output of the above would be:

parent2
share|improve this answer
    
Thank you very much. But i have to write a script as where we have to pass only "child" not a full path as "root/parent/parent2/child" If we have any options to get in that way please let me know. Thanks –  kumar Oct 25 '12 at 4:36
    
@kumar Well, you said that you are "able to to display child tag details", from which I understand that you already have code to take the name of the child node and get a reference to it. SelectSingleNode() in my answer was just an example, you should replace it with the actual code that you have. Or, if I misunderstood, then perhaps you could edit the question to show what code you do have and what it does? –  Indrek Oct 25 '12 at 6:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.