使用groovy问题创建XML

时间:2017-02-16 10:23:15

标签: xml groovy

我想创建一个XML并将其保存在文件中。下面是代码的一部分

  def fileWriter = new FileWriter("c:/temp/test.xml")
  def xml = new groovy.xml.MarkupBuilder(fileWriter).event {
    event ("xmlns" : "http://www.hp.com/2009/software/opr/data_model") {
      state("closed")
    }
//    fileWriter.close();        
  }
  fileWriter.close();

这很好用,并在c:\ temp \ Directory。

中创建一个XML文件

这就是它的外观。

<event>
<event xmlns='http://www.hp.com/2009/software/opr/data_model'>
<state>closed</state>
</event>
</event>

但我想要的只是

<event xmlns='http://www.hp.com/2009/software/opr/data_model'>
<state>closed</state>
</event>

如何避免XML输出中的第一个和最后一个?

2 个答案:

答案 0 :(得分:2)

摆脱额外的event

import groovy.xml.MarkupBuilder

def fileWriter = new FileWriter("c:/temp/test.xml")

new MarkupBuilder(fileWriter).event("xmlns": "http://www.hp.com/2009/software/opr/data_model") {
    state("closed")
}

fileWriter.close();

答案 1 :(得分:2)

你召唤两次事件,所以你得到两个事件标签 叫它一次,你只得到一个 除此之外,我建议使用 $Path = "D:\My Programs\2017\MeetSchedAssist\Meeting Schedule Assistant" $Text = "ID_STR_THIS_VERSION" $PathArray = @() $Results = "D:\Results.txt" # But I want to IGNORE "resource.h" # But I want to filter for *.h AND *.cpp # First you collect the files corresponding to your filters $files = Get-ChildItem -Path "$Path\*" -Include "*.cpp", "*.h" | Where-Object { $_.Attributes -ne "Directory"} # Then, you enumerate these files and search for your pattern $files | ForEach-Object { If ((Get-Content $_.FullName) | Select-String -Pattern $Text) { $PathArray += $_.FullName } } Write-Host "Contents of ArrayPath:" $PathArray | ForEach-Object {$_} 之类的

withWriter()

然后无需手动关闭作家。