I have defined an XML string using
$str = "<a><b></b></a>"
Now I want to load it into a [xml] variable to be able to manipulate it's nodes etc. The row below results in an error...
$str = [xml]"<a><b></b></a>"
How do I do this?
I have defined an XML string using
$str = "<a><b></b></a>"
Now I want to load it into a [xml] variable to be able to manipulate it's nodes etc. The row below results in an error...
$str = [xml]"<a><b></b></a>"
How do I do this?
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.
Casting a string also worked for me:
...and I ran it with your string and it worked fine...
Full Image
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