Home > Blockchain >  How can I properly create this xml file in Powershell using XmlWriter()?
How can I properly create this xml file in Powershell using XmlWriter()?

Time:07-06

I want to create an xml document like this using XmlWriter() in powershell but I'm having trouble, this is the expected output:

<Item version="1">
  <Name>Myproject</Name>
  <GUID>4821CC01-CDB0-4FD7-9F1E-0B1EDF32ACE9</GUID>
</Item>

Current code:

$xmlsettings = New-Object System.Xml.XmlWriterSettings
$xmlsettings.Indent = $true
$XmlWriter = [System.XML.XmlWriter]::Create("$PSScriptRoot\Myproject.xml", $xmlsettings)

# As mentioned above, I don't want the default output of WriteStartDocument(), so I used this
$xmlWrite.WriteStartElement("Item") 
$xmlWrite.WriteAttributeString("Version", "1.0")
$xmlWriter.WriteElementString("Name",$myProject) # I have a string variable containing the project name

<#From here it throws the error: Exception calling "WriteElementString" with "2" argument(s): "Token StartElement in state EndRootElement would result in an
     | invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if
     | you want to write an XML fragment."#>
$xmlWriter.WriteElementString("GUID",(New-Guid).Guid.ToUpper())
$xmlWriter.WriteEndElement()

$xmlWriter.Flush()
$xmlWriter.Close()

Error output of the above code:

<?xml version="1.0" encoding="utf-8"?>
<Name>Myproject</Name>

Do not know why still output the contents of WriteStartDocument(), I'm sure I didn't type the wrong code and this obviously doesn't apply the indentation.

Anyone willing to help? thanks in advance!

CodePudding user response:

Try this -> $xmlWriter.WriteElementString("Name","$($myProject)")

CodePudding user response:

Your current code does not compile, but with corrected variable names it works fine.

if you need remove xml version just add $xmlsettings.OmitXmlDeclaration = $true

$myProject = 'Myproject'
$path = "c:\temp\Myproject.xml"

$xmlsettings = New-Object System.Xml.XmlWriterSettings
$xmlsettings.Indent = $true

$xmlWriter = [System.XML.XmlWriter]::Create($path, $xmlsettings)
$xmlWriter.WriteStartElement("Item") 
$xmlWriter.WriteAttributeString("Version", "1.0")
$xmlWriter.WriteElementString("Name",$myProject)
$xmlWriter.WriteElementString("GUID",(New-Guid).Guid.ToUpper())
$xmlWriter.WriteEndElement()

$xmlWriter.Flush()
$xmlWriter.Close()

Result

<?xml version="1.0" encoding="utf-8"?>
<Item Version="1.0">
  <Name>Myproject</Name>
  <GUID>3CA7FBFA-1585-44A1-B4D9-D59E9371FE1B</GUID>
</Item>
  • Related