15

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?

2
  • 4
    I'm not seeing any error from that line. Have you previously strongly typed the $str variable or something? Try putting the type before the variable to (re)strongly type the variable: [xml]$str = "<a><b></b></a>" (or [xml]$str = [xml]"<a><b></b></a>" ) Commented Oct 14, 2010 at 17:31
  • Same here. It works for me as you have typed it above. Commented Oct 14, 2010 at 23:53

4 Answers 4

25

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

Sign up to request clarification or add additional context in comments.

2 Comments

It's all about loading XML from a FILE. I want to load it from a STRING.
How about you post the error your getting then, because I was able to load the string in my powershell just fine. Also take it easy on the caps, the references inside those articles STILL APPLY (see how annoying the caps are). I'll update my question for you
8

Try this

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

Comments

6

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

1 Comment

Cool how you removed the first line programmatically.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.