rickythefox
rickythefox

Reputation: 6861

Loading XML string with PowerShell

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

Answers (4)

jared
jared

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

Urda
Urda

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.

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

Casting a string also worked for me:

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


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

Upvotes: 25

JJJCoder
JJJCoder

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

Awadhesh Verma
Awadhesh Verma

Reputation: 79

Try this

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

Upvotes: 8

Related Questions