1 Pluspunkt 0 Minuspunkte

Wie kann ich die XML Ausgabe in einem String speichern anstatt in eine Datei zu schreiben?

$xmlWriter = New-Object System.XMl.XmlTextWriter('C:\Test.xml',$Null)

$xmlWriter.Formatting = 'Indented'

$xmlWriter.Indentation = 1

$XmlWriter.IndentChar = "`t"

$xmlWriter.WriteStartDocument()

$xmlWriter.WriteComment('Car List')

$xmlWriter.WriteStartElement('prtg')
#$XmlWriter.WriteAttributeString('Owner', 'Jay Leno')

$xmlWriter.WriteStartElement('result')
#$xmlWriter.WriteAttributeString('VIN', '123567891')

$xmlWriter.WriteElementString('Make','Ford')
$xmlWriter.WriteElementString('Model','Taurus')
$xmlWriter.WriteElementString('Year','2012')

$xmlWriter.WriteEndElement()

$xmlWriter.WriteStartElement('result')
#$xmlWriter.WriteAttributeString('VIN', '123555567891')

$xmlWriter.WriteElementString('Make','BWM')
$xmlWriter.WriteElementString('Model','328i')
$xmlWriter.WriteElementString('Year','2015')

$xmlWriter.WriteEndElement()

$xmlWriter.Flush()

$xmlWriter.Close()
von  

1 Antwort

0 Pluspunkte 0 Minuspunkte

Um den XML-Text in einen String zu speichern, anstatt ihn in eine Datei zu schreiben, kannst du System.IO.StringWriter zusammen mit System.Xml.XmlTextWriter verwenden.

$stringWriter = New-Object System.IO.StringWriter
$xmlWriter = New-Object System.XMl.XmlTextWriter($stringWriter)

$xmlWriter.Formatting = 'Indented'

$xmlWriter.Indentation = 1

$XmlWriter.IndentChar = "`t"

$xmlWriter.WriteStartDocument()

$xmlWriter.WriteComment('Car List')

$xmlWriter.WriteStartElement('prtg')
#$XmlWriter.WriteAttributeString('Owner', 'Jay Leno')

$xmlWriter.WriteStartElement('result')
#$xmlWriter.WriteAttributeString('VIN', '123567891')

$xmlWriter.WriteElementString('Make','Ford')
$xmlWriter.WriteElementString('Model','Taurus')
$xmlWriter.WriteElementString('Year','2012')

$xmlWriter.WriteEndElement()

$xmlWriter.WriteStartElement('result')
#$xmlWriter.WriteAttributeString('VIN', '123555567891')

$xmlWriter.WriteElementString('Make','BWM')
$xmlWriter.WriteElementString('Model','328i')
$xmlWriter.WriteElementString('Year','2015')

$xmlWriter.WriteEndElement()

$xmlWriter.Flush()

$xmlWriter.Close()

# Konvertiere den StringWriter in einen String
$xmlString = $stringWriter.ToString()

# Ausgabe des XML-Strings
Write-Output $xmlString
von (542 Punkte)