Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading XML string with PowerShell

Tags:

powershell

xml

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?

like image 604
rickythefox Avatar asked Oct 14 '10 16:10

rickythefox


People also ask

How do I load XML in PowerShell?

One way to read an XML document in PowerShell is to typecast a variable to the type [xml]. To create this variable, we can use the Get-Content cmdlet to read all of the text in an XML document. To typecast the output of Get-Content we can simply prepend the text [xml] before the variable.

Can PowerShell parse XML?

Another way to use PowerShell to parse XML is to convert that XML to objects. The easiest way to do this is with the [xml] type accelerator. By prefixing the variable names with [xml] , PowerShell converts the original plain text XML into objects you can then work with.

How do I update XML in PowerShell?

To update the specific XML node using PowerShell, we first need to select that node with the attribute with SelectSingleNode() method. We have below the XML file from the link stored in SampleXml. XML on C:\Temp location. The above commands will load the XML file and select node with attribute value 'bk102'.


2 Answers

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

like image 65
Urda Avatar answered Oct 05 '22 01:10

Urda


Try this

$xmlcontent = variable which holds xml data in string
$xml = New-Object -TypeName System.Xml.XmlDocument
$xml.LoadXml($xmlcontent)
like image 29
Awadhesh Verma Avatar answered Oct 05 '22 02:10

Awadhesh Verma