1

I have an XML file and I have to retrieve all its attributes.

How to achieve that without knowing their names and values?

My XML file structure looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<TEST0>
    <TEST1>
        <TEST2>
            <TEST3 name="myname1" value="myvalue1" />
            <TEST3 name="myname2" custVal="myvalue2" />
        </TEST2>
    </TEST1>
    <TEST4>
      <TEST5 name="myname3" custVal="myvalue3"/>
    </TEST4>
</TEST0>

This is what I tried:

 [System.Xml.XmlDocument] $xmlContent = new-object System.Xml.XmlDocument;
    $file = resolve-path('./myxml.xml');
    $xmlContent.load($file)
    $nodelist = $xmlContent.selectnodes("//*"); 

    foreach ($node in $nodelist) {
       Write-Host $node.Name " = " $node.Value
    }

This is the expected result:

myname1 = myvalue1
myname2 = myvalue2
myname3 = myvalue3

But this is my result:

myname1 = myvalue1
myname2 = 
myname3 = 

THE PROBLEM: It searches for attribute named value, but not all my attributes are named like this, some of them are custom and I don't know the names. What can i do in this case?

UPDATE: To get the actual attributes names and values just add .Attribues in the loop:

 foreach ($node in $nodelist) {
       Write-Host $node.Name " = " $node.Value
    }

This returns:

name = myname1 
value = myvalue1
name = myname2 
custVal = myvalue2
name = myname3 
custVal = myvalue3

1 Answer 1

2

You could do:

[xml]$xmlContent = Get-Content -Path (Resolve-Path -Path './myxml.xml') -Raw

$nodelist = $xmlContent.SelectNodes("//*[@name]")

foreach ($node in $nodelist) {
    Write-Host ('{0} = {1}' -f $node.Name, $node.Attributes[1].'#text')
}

Result:

myname1 = myvalue1
myname2 = myvalue2
myname3 = myvalue3
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that worked! :) . I also just realised If i need to get the actual attribute name I can use ($node in $nodelist.Attributes) { Write-Host $node.Name " = " $node.Value } This returns: name=myname1 value=myvalue1 name=myname2 custVal=myvalue2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.