I have a XML document:
<Root>
<ItemA Name="1" />
<ItemB Name="2" />
<ItemC Name="3" />
</Root>
and a powershell script accessing data from that document. I need to iterate by the children of Root and print the element names of its children. Example:
$xml = [xml](gc MyXmlFile.xml);
$xml.Root.Name
# prints "Root"
$xml.Root.ChildNodes | foreach { $_.Name }
# prints 1 2 3 because Item(A|B|C) have an attribute named "Name"
# I need to print ItemA ItemB ItemC
Update: As MrKWatkins correctly pointed out below in this case I could use the LocalName property instead. However this will not work if I'm using namespaces of if I also have a LocalName attribute in my XML. I would like to know if exists a solution for this problem that always works no matter the XML file.
One way to read an XML document in PowerShell is to typecast a variable to the type [xml]. To create this variable, we can use the Get-Content cmdlet to read all of the text in an XML document. To typecast the output of Get-Content we can simply prepend the text [xml] before the variable.
Another way to use PowerShell to parse XML is to convert that XML to objects. The easiest way to do this is with the [xml] type accelerator. By prefixing the variable names with [xml] , PowerShell converts the original plain text XML into objects you can then work with.
The Select-Xml cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.
PowerShell has a few different ways to query XML files, but this tip will focus on the Select-Xml cmdlet and XPath syntax. XPath is a syntax for defining parts of an XML document. XPath has been around since 1999 and has been used as a standard way to query XML documents. XPath defines an XML document as a tree.
You can do something like this:
$xml.Root | gm -MemberType property | select Name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With