powershell XML Writer嵌套循环

时间:2013-05-13 12:57:09

标签: xml powershell

我有一个powershell脚本,我正在尝试为导入构建一个冗长的XML文件。我遇到的问题是,在运行时,XML的输出具有所有打开的标记,但从未关闭它们直到结束。即使我有“WriteEndElement”函数按我想要的顺序关闭标记,但在完成所有“WriteStartElement”标记之前,它并不尊重这些标记。即,输出看起来像

<1>
  <2>
    <3>
      <4>
      </4>
    </3>
  </2>
</1>

但是在我的代码中,3的结束应该在4开之前到来。
我的剧本:

$groups = gc "./groups.txt"
$regions = gc "./regions.txt"
$types = gc "./Types.txt"

$output = "./Workgroups.txt"
$xmlOut = "c:\wgIMPORT.xml"
$wgExt = 60001


# Create The Document
$XmlWriter = New-Object System.XMl.XmlTextWriter($xmlOut,$Null)
# Set The Formatting
$xmlWriter.Formatting = "Indented"
$xmlWriter.Indentation = "4"
# Write the XML Decleration
$xmlWriter.WriteStartDocument()
# Set the XSL
$XSLPropText = "type='text/xsl' href='style.xsl'"
$xmlWriter.WriteProcessingInstruction("xml-stylesheet", $XSLPropText)
# Write Root Element
$xmlWriter.WriteStartElement("Scenarios")
# Write the Document
$xmlWriter.WriteStartElement("Scenario")
$xmlWriter.WriteElementString("Schedule","Immediate")



for($i=0;$i -lt $groups.Count;$i++){
    for($j=0;$j -lt $regions.Count;$j++){
        for($k=0;$k -lt $types.Count;$k++){ 
            #$groups[$i] + "_" + $regions[$j] + "_" + $types[$k] >> $output
            $wg = $groups[$i] + "_" + $regions[$j] + "_" + $types[$k]
            $xmlWriter.WriteStartElement("WorkgroupCommand")
            $XmlWriter.WriteAttributeString("Name","$wg")
            $XmlWriter.WriteAttributeString("Extension","$wgExt")
            $XmlWriter.WriteAttributeString("HasQueue","1")
            $xmlWriter.WriteStartElement("Attributes")
            $xmlWriter.WriteStartElement("Attribute")
            $XmlWriter.WriteAttributeString("Value","206")
            $xmlWriter.WriteEndElement # end Attribute
            $xmlWriter.WriteElementString("Value","TestSkill")
                $xmlWriter.WriteEndElement # end Attributes
            $xmlWriter.WriteStartElement("Members")
            $xmlWriter.WriteElementString("Member","tonkaadmin")
            $xmlWriter.WriteEndElement # end  </Members> Command
            $xmlWriter.WriteEndElement # end Workgroup Command
            $wgExt++
        }
    }
}    

$xmlWriter.WriteEndElement # end Scenario
# Write Close Tag for Root Element
$xmlWriter.WriteEndElement # end Scenarios
# End the XML Document
$xmlWriter.WriteEndDocument() 
# Finish The Document
$xmlWriter.Finalize
$xmlWriter.Flush
$xmlWriter.Close()

1 个答案:

答案 0 :(得分:1)

使用

$xmlWriter.WriteEndElement()

而不是

$xmlWriter.WriteEndElement

应解决您的问题