【发布时间】:2017-01-11 13:30:55
【问题描述】:
我需要使用 Perl 将如下嵌套的 XML 格式转换为 Java:
<invoke name="name1" operation="operation1" displayName="Invoke1" id="6">
<input>
<parameter name="Value" variable="Value"/>
<parameter name="ID" variable="ID"/>
</input>
<output>
<parameter name="Return" variable="Return"/>
</output>
</invoke>
<switch name="..." displayName="..." id="13">
<case id="14">
<condition expressionLanguage="..."><![CDATA[(c1)]]></condition>
</case>
<otherwise id="106">
<switch name="..." displayName="..." id="15">
<case id="16">
<condition expressionLanguage="..."><![CDATA[(c2)]]></condition>
<switch name="..." displayName="..." id="19">
<case id="20">
<condition expressionLanguage="..."><![CDATA[(c3) >0)]]></condition>
</case>
<otherwise id="106"> </otherwise>
</switch>
</case>
<otherwise id="107">
<switch name="..." displayName="..." id="33">
<case id="64">
<condition expressionLanguage="..."><![CDATA[(c4)]]></condition>
</case>
<otherwise id="108"> </otherwise>
</switch>
</otherwise>
</switch>
</otherwise>
</switch>
预期输出如下:
<invoke name="name1" operation="operation1" displayName="Invoke1" id="6">
<input>
<parameter name="Value" variable="Value"/>
<parameter name="ID" variable="ID"/>
</input>
<output>
<parameter name="Return" variable="Return"/>
</output>
</invoke>
if(c1) {
}else{
if(c2) {
if(c3) {
}else{
}
}else{
if(c4) {
}else{
}
}
}
我认为可以通过 4 个步骤来实现:
- 读取 XML 文件 -> 获取第一个 switch1 块 -> 转换为 if--else
- 获取 case1 块,否则获取 switch1 块的 1 块
- 从第 1 步为 case1 块和其他 1 块实现递归
- 读取 XML 文件的其余部分并从 s1 执行相同操作
在这种情况下,我实际上很难进行递归。一些 Perl 专家可以在这里帮助我吗?
【问题讨论】:
-
您可以尝试编写一个函数
process_switch,它采用XML 树节点(XML::Twig或Mojo::DOM将是解析文件的好选择)和缩进级别。使用文件中的顶部switch元素调用它。获取节点的第一个case子节点。获取case的condition子级并将其打印为"\t" x $indentation . if( COND ) {。如果case具有switch子元素,则使用$indentation+1递归调用自己。关闭if块并对otherwise执行相同操作(如果存在)。 -
您好 mbethke,感谢您花时间回答我的问题。我的看法和你一样,但难点是如果在 Case 块中有另一个 sub-otherwise 块,如何获得 else 块。你能帮我写一个示例 perl 代码来解决这个问题吗?
标签: java regex xml perl xml-parsing