Reputation: 6861
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?
Upvotes: 15
Views: 61298
Reputation: 11
You can also do it like this:
[XML]$str = "<a><b></b></a>"
Now $str
is an XML object:
$str | GM
TypeName System.Xml.XmlDocument
Upvotes: 1
Reputation: 5411
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
Upvotes: 25
Reputation: 16986
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
Upvotes: 5
Reputation: 79
Try this
$xmlcontent = variable which holds xml data in string
$xml = New-Object -TypeName System.Xml.XmlDocument
$xml.LoadXml($xmlcontent)
Upvotes: 8