Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing XmlElement names in PowerShell

Tags:

powershell

xml

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.

like image 805
Pedro Jacinto Avatar asked Aug 22 '11 15:08

Pedro Jacinto


People also ask

How do I display XML in PowerShell?

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.

How to Parse XML file PowerShell?

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.

Which PowerShell command does support XML?

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.

What is XPath in PowerShell?

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.


1 Answers

You can do something like this:

$xml.Root | gm -MemberType property | select Name
like image 169
manojlds Avatar answered Sep 28 '22 14:09

manojlds