Loading XML string with PowerShell

Try this

$xmlcontent = variable which holds xml data in string
$xml = New-Object -TypeName System.Xml.XmlDocument
$xml.LoadXml($xmlcontent)

For the benefit of searchers, if you have a top line of xml that includes formatting (rather than straight in at the root node) info you need to remove the top line before you can cast it

e.g.

<?xml version="1.0" encoding="utf-8"?>
<Courses>
  <CourseEntry Type="Mandatory" Name="Math"/>
  <CourseEntry Type="Mandatory" Name="Coding" />
  <CourseEntry Type="Optional" Name="Economics" />
  <CourseEntry Type="Optional" Name="History" />
</Courses>

Requires:

$xmlFile = Get-Content "*.xml"
$xmlFileMinusFormatData = $xmlFile[1..($xmlFile.Length - 1)] #we need to remove the first line
$usableXml = [xml]$xmlFileMinusFormatData # Convert to xml for easy handling
$usableXml.Courses.CourseEntry.Count # just a count of rows

The code in your question seems to work for me. I just added test inside my string to show I can access the value, but it should work without it, too.

Yes I added test, but you can see my example workedFull Image

Casting a string also worked for me:

Again, I added test to show that I can access XML membersFull Image


...and I ran it with your string and it worked fine... ...notice there was an empty return?Full Image

Tags:

Xml

Powershell