Davis8988
Davis8988

Reputation: 696

How to read XML file that contains a header using PowerShell

I am trying to read this XML file using PowerShell:

<?xml version='1.1' encoding='UTF-8'?>  

<Root>  
  <element1>  
    <string>name</string>  
  </element1>  
  <version>3.2.1</version>  
</Root>  

The PowerShell command that I use:

$fileContent = New-Object XML
$fileContent.Load($filePath)  # $filePath contains the path to the XML file above

and I get the following error:

Exception calling "Load" with "1" argument(s): "Version number '1.1' is invalid.

If I remove the header <?xml version='1.1' encoding='UTF-8'?> or comment it (<!-- <?xml version='1.1' encoding='UTF-8'?> -->) I don't get the error any more. Problem is that I need that header.

How can I read the XML file with the header using PowerShell?

Upvotes: 2

Views: 1988

Answers (1)

Paweł Dyl
Paweł Dyl

Reputation: 9143

XML version 1.1 is not supported in .NET. See following demo and explanations:

@'
<?xml version='1.1' encoding='UTF-8'?>  

<Root>  
  <element1>  
    <string>name</string>  
  </element1>  
  <version>3.2.1</version>  
</Root> 
'@ | Out-File Demo.xml

$content = (Get-Content .\Demo.xml)
[xml]$content #fails, not supportes
#if 'magical' features of v1.1 are not used, change version to 1.0
$fixed = $content.Replace('<?xml version=''1.1'' encoding=''UTF-8''?>','<?xml version=''1.0'' encoding=''UTF-8''?>')
[xml]$fixed #this should work

I do not recommend reading specification, because XML 1.1 is dead. I would recommend this blog post about XML 1.1.

Upvotes: 6

Related Questions