1

XML 文件如下所示:

<?xml version="1.0"?>
<application name="pos">
<artifact id="123" type="war" cycle="Release7-Sprint1">
<jira/>
<jenkins/>
<deployment/>
<scm>
  <transaction id="1234" user="">
    <file name=""/>
    <file name=""/>
  </transaction>
</scm>
</artifact>
</application>

当我使用属性(名称)的硬编码值而不是使用变量时,我的代码如下所示并且工作正常。我正在引用该行( my $query =
'//application[@name="pos"]'; )

my $manifestDoc = $manifestFileParser->parse_file($manifestFile);
my $changeLogDoc = $changeLogParser->parse_file($changeLogXml );
my $changeLogRoot = $changeLogDoc->getDocumentElement;

#my $applicationName = pos;
my $query  = '//application[@name="pos"]';
my $applicationNode = $manifestDoc->findnodes($query);

my $artifactNode = $manifestDoc->createElement('artifact');
$artifactNode->setAttribute("id",$artifactID);
$artifactNode->setAttribute("type",$artifactType);
$artifactNode->setAttribute("cycle",$releaseCycle);
$applicationNode->[0]->appendChild($artifactNode);

但是,如果我修改 $query 变量以使用变量 ($applicationName) 而不是属性的硬编码值,它会给我一个编译错误,如下所示:

无法在 updateManifest.pl 行的未定义值上调用方法“appendChild”

修改后的代码:

 my $applicationName = "pos" ;
 my $query  = '//application[@name="$applicationName"]';

不知道出了什么问题。跟引号有关系吗?任何帮助深表感谢。

4

1 回答 1

1

The expression '//application[@name="$applicationName"]' means the literal string with those contents – no variables are interpolated with single quotes. If you'd use double quotes, then both @name and $applicationName would be interpolated.

You have three options:

  1. Use double quotes, but escape the @:

    qq(//application[\@name="$applicationName"])
    

    The qq operator is equivalent to double quotes "…" but can have arbitrary delimiters, which avoids the need to escape the " inside the string.

  2. Concatenate the string:

    '//application[@name="' . $applicationName . '"]'
    

    This often has a tendency to be hard to read. I'd avoid this solution.

  3. Use a sprintf pattern to build the string from a template:

    sprintf '//application[@name="%s"]', $applicationName
    

    If you don't already know printf patterns, you can find them documented in perldoc -f sprintf.

于 2014-02-19T10:28:58.953 回答