Reputation: 211
I have a PowerShell script:
$xmlString="<root>
<section>
<node id='1'>AAA</node>
<node id='2'>BBB</node>
<node id='3'>CCC</node>
</section>
</root>"
$xml = New-Object -TypeName System.Xml.XmlDocument
$content = $xml.LoadXml($xmlString)
Value of $content
is null
Inner Exception in $xml
variable is <Error retrieving property - ArgumentException>
I have checked whether string starts with [System.Text.Encoding]::UTF8.GetPreamble()
but it does not.
Can you please tell, what it is correct way to convert such string to XML?
Upvotes: 4
Views: 10613
Reputation: 3036
You can directly cast the string to XmlDocument
like this:
[xml]$xmlString="<root>
<section>
<node id='1'>AAA</node>
<node id='2'>BBB</node>
<node id='3'>CCC</node>
</section>
</root>"
If you want to keep the format of the variable, you can ofc just do it like this:
$xmlString="<root>
<section>
<node id='1'>AAA</node>
<node id='2'>BBB</node>
<node id='3'>CCC</node>
</section>
</root>"
[xml]$content = $xmlString
To follow up on @AnsgarWiechers comment, if you really want to use LoadXML
, this is how it should look:
$xmlString=
"<root>
<section>
<node id='1'>AAA</node>
<node id='2'>BBB</node>
<node id='3'>CCC</node>
</section>
</root>"
$xml = New-Object -TypeName System.Xml.XmlDocument
$xml.LoadXml($xmlString)
LoadXml
will load a value from the given string to the $xml
variable that calls the method.
It doesn't return any value, but saves it to $xml
.
Upvotes: 6
Reputation: 17161
ConvertFrom-Xml
is what you need!
It's available from the PowerShell Gallery as part of Avande.CoolFunctions
$xmlString = @"
<root>
<section>
<node id='1'>AAA</node>
<node id='2'>BBB</node>
<node id='3'>CCC</node>
</section>
</root>
"@
$xmlString | ConvertFrom-Xml
Upvotes: 1