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