我正在尝试使用powershell和XmlWriter编写嵌套的XML文件。但是输出并不是我所期望的,它也不符合我在代码中逻辑设置它的方式。我知道它有点长,但请看下面的代码:
function newXML($output_file, $hubs_array){
#create directory
new-item -path "$outage_dir\$current_year\$current_month" -type directory -force
# Create The Document and format
$XmlWriter = New-Object System.XMl.XmlTextWriter($output_file,$Null)
#format xml
$xmlWriter.Formatting = [System.Xml.Formatting]::Indented
# Write the XML Decleration
$xmlWriter.WriteStartDocument()
# Set the XSL
$XSLPropText = "type='text/xsl' href='style.xsl'"
$xmlWriter.WriteProcessingInstruction("xml-stylesheet", $XSLPropText)
# <identifier><start of outage><end of outage><outage as perc>
# Write Root Element
$xmlWriter.WriteStartElement("Hubs")
# Write the Document
foreach ($hub in $hubs_array){
$xmlWriter.WriteStartElement("Hub")
$xmlWriter.WriteAttributeString("name",$hub.hubname)
foreach($device in $hub.devices){
$xmlWriter.WriteStartElement("Device")
$xmlWriter.WriteElementString("identifier", $device.device_id)
$xmlWriter.WriteEndElement
$xmlWriter.WriteElementString("sla", $device.SLA)
$xmlWriter.WriteEndElement
$xmlWriter.WriteElementString("outage_as_perc", $device.down_4dp)
$xmlWriter.WriteEndElement
$xmlWriter.WriteStartElement("Outages")
$xmlWriter.WriteAttributeString("total",$device.outages)
foreach($outage in $device.outagesArray){
$xmlWriter.WriteStartElement("Outage")
$xmlWriter.WriteElementString("start_of_outage", $outage.down_start)
$xmlWriter.WriteEndElement
$xmlWriter.WriteElementString("end_of_outage", $outage.down_end)
$xmlWriter.WriteEndElement
$xmlWriter.WriteElementString("total_downtime", $outage.downtime)
$xmlWriter.WriteEndElement
#close tag for outage
$xmlWriter.WriteEndElement
}
#close tag for outages
$xmlWriter.WriteEndElement
#close tag for device
$xmlWriter.WriteEndElement
}
#close tag for hub
$xmlWriter.WriteEndElement
}
#close tag for hubs
$xmlWriter.WriteEndElement
$xmlWriter.WriteEndDocument()
# Finish The Document
$xmlWriter.Finalize
$xmlWriter.Flush
$xmlWriter.Close()
}
我认为这将按以下格式输出:
<Hubs>
<Hub>
<Device>
<identifier></>
<sla></>
<outage_as_perc></>
<Outages total="2">
<outage>
</outage>
</Outages>
</Device>
</Hub>
</Hubs>
我正在循环的事实似乎弄乱了它,但我不知道为什么......
我得到的结果是:
<Hubs>
<Hub>
<Device>
<identifier></>
<sla></>
<outage_as_perc></>
<Outages total="2">
<outage>
<outage>
<outage>
<outage>
<outage>
</outage>
</outage>
</outage>
</outage>
</outage>
</Outages>
</Device>
</Hub>
</Hubs>
提前致谢,对不起,长期阅读!!!
答案 0 :(得分:1)
$xmlWriter.WriteEndElement()
而不是
$ xmlWriter.WriteEndElement
should fix your problem
中的同样问题