我们有一个TCL脚本来生成XML文件吗?

时间:2016-12-27 06:45:08

标签: xml tcl itcl

  

我使用tcldom创建了一个脚本:

package require utils
package require testrunscheduler
package require tdom
tla::TSConfig::init -schedulerContext "Reporting" -environment production
tla::TSDBFactory::getConnection db
set testCaseList [$db doSQL "SELECT root_name,suite_name,case_name FROM ics where test_type = 'tce' limit 1"]
set item [join $testCaseList ""]

set doc [dom createDocument testCases]
set root [$doc documentElement]
set subnode [$doc createElement testCase]
$root appendChild $subnode

foreach item $item {
set node [$doc createElement root]
$node appendChild [$doc createTextNode $item]
$subnode appendChild $node
}
  

我得到的输出是:

<testCases>
    <testCase>
        <root>SPB</root>
        <root>subscriberServices</root>
        <root>jmsServices</root>
    </testCase>
</testCases>
  

但我希望输出如下:

<testCases>
    <testCase>
        <root>SPB</root>
        <suite>subscriberServices</suite>
        <case>jmsServices</case>
    </testCase>
</testCases>
  

我为此使用了foreach,但它只对root用户,我可能会遗漏,这个结构会迭代自己,并从sql查询的用户输入增长。

<testCases>
    <testCase>
        <root>demoRoot</root>
        <suite>demoSuite</suite>
        <case>demoCase</case>
        <testCase>test_demo001</testCase>
    </testCase>
    <testCase>
        <root>demoRoot</root>
        <suite>demoSuite</suite>
        <case>demoCase</case>
        <testCase>test_demo002</testCase>
    </testCase>
</testCases>

请帮助我获得这种输出,这非常繁琐,以获得重复但具有一种结构的输出。

1 个答案:

答案 0 :(得分:0)

package require tdom

set data {
    {demoRoot1 demoSuite1 demoCase1}
    {demoRoot2 demoSuite2 demoCase2}
}

set doc [dom createDocument testCases]
set root [$doc documentElement]

dom createNodeCmd elementNode testCase
dom createNodeCmd elementNode root
dom createNodeCmd elementNode suite
dom createNodeCmd elementNode case
dom createNodeCmd textNode t

foreach line $data {
    lassign $line _root suite case
    # or (if you don't have lassign) foreach {_root suite case} $line break

    $root appendFromScript {
        testCase {
            root {t $_root}
            suite {t $suite}
            case {t $case}
            testCase {t [format {test_demo%03d} [incr num]]}
        }
    }
}

$doc asXML

输出:

<testCases>
    <testCase>
        <root>demoRoot1</root>
        <suite>demoSuite1</suite>
        <case>demoCase1</case>
        <testCase>test_demo001</testCase>
    </testCase>
    <testCase>
        <root>demoRoot2</root>
        <suite>demoSuite2</suite>
        <case>demoCase2</case>
        <testCase>test_demo002</testCase>
    </testCase>
</testCases>

有关更多示例,请参阅Wiki上的教程。

文档: breakforeachformatifincrlassignpackagesettdom (package)