1

有什么方法可以检查给定元素 X 是否传递给宏定义。我有一个案例来决定元素 X 是必需的还是可选的。为了实现这一点,我将元素设为在所有情况下都是可选的,但我想在元素丢失的情况下进行验证,如果它允许丢失:-)。

宏看起来像这样:

<macrodef name="test">
<attribute name="attribute1"/> 
......
<attribute name="attributeN/>

<element name="X" optional="true/> 
<element name="Y" optional="true/>

<sequential>
<local>
<!--here check if the element <X/> is passed -->  
</local>
</sequential>
</macrodef>



<test attribute1="1", attributeN="N">
<!--Here do not provide element X. Only provide Y-->
<Y>
<nestedY1>Some text1</nestedY1>
<nestedY2>Some text2</nestedY2>
</Y>
</test>

元素 X 看起来就像元素 Y。我的意思是,如果它存在,它将包含另一个嵌套元素。

也许我理解这个概念的方式是错误的。我将尝试再举一个例子。目前元素 X 是强制性的,我的任务是使其在某些情况下是可选的,但在另一些情况下是强制性的。我希望能够以两种方式使用宏,但我不知道如何实现此任务:

<macrodef name="test">
<attribute name="attribute1"/> 

<element name="X"/> 
<element name="MandatoryX" optional="true/>

<sequential>
<local>
<!--here check if the element <MandatoryX/> is passed and if Yes than make sure that element X is passed too-->  
</local>
</sequential>
</macrodef>

<test attribute1="1">
<!--Here MandatoryX is missing and X can be missing too-->
</test>

or

<test attribute1="1">
<MandatoryX>In case MandatoryX is present, than element X must be present too</MandatoryX>
<X>Here X is mandatory</X>
</test>
4

1 回答 1

0

我想出了一个办法。有点笨拙,但对我有用。关键是使用<echoxml>任务将宏元素写入文件,然后读取文件并在其中查找一些模式。我写<stuff></stuff>围绕宏元素。当没有提供宏元素时,该stuff元素被写为 simple <stuff />,并且可以搜索。

请注意,我也在使用 antcontrib,因此该<if>块。

<macrodef name="processFiles">
  <attribute name="workDir"/>
  <attribute name="tempDir"/>
  <element name="extra-deletes" optional="true"/>
  <sequential>
    <echoxml file="@{tempDir}/extra-deletes.xml"><stuff><extra-deletes/></stuff></echoxml>
    <local name="extra-deletes-prop"/>
    <loadfile property="extra-deletes-prop" srcfile="@{tempDir}/extra-deletes.xml"/>

    <if>
      <not><contains string="${extra-deletes-prop}" substring="&lt;stuff /&gt;"/></not>
      <then>
        <delete>
          <fileset dir="@{workDir}">
            <extra-deletes/>
          </fileset>
        </delete>
      </then>
    </if>
  </sequential>
</macrodef>

这个宏会被调用一些表达式<filename .../>来识别要删除的文件。(这源自一个更复杂的脚本,但基本上每个项目都有一些文件模式要删除,而其他项目有额外的、特定于项目的删除模式。)

所以它会被这样调用:

<processFiles workDir="..." tempDir="...">
  <extra-deletes>
    <or>
      <filename name="..."/>
      <filename regex="..."/>
    </or>
  </extra-deletes>
</processFiles>

...或者在没有“额外删除”执行的情况下,

<processFiles workDir="..." tempDir="..."/>
于 2021-09-16T21:58:05.237 回答