【问题标题】:Perl parse xml with XML::LibXML dynamic nodePerl 使用 XML::LibXML 动态节点解析 xml
【发布时间】:2014-05-12 12:28:03
【问题描述】:

我有这个 xml 文件,我需要获取类别、属性和测试用例, 我使用 XML::LibXML 和 findnodes 成功完成了它 问题是有时结构不同,所以可能会有更多 test-suite & results nodes 那么 findnodes 中的节点不正确。

那么处理它的最佳方法是什么? 如果我不知道正确的基本起始节点,则不确定如何搜索 type="Fixture(这是具有我需要的信息的节点)。

<test-A>
 <test-suite type="Project">
    <results>
        <test-suite type="Setup">
          <results>
            <test-suite type="Fixture>
              <categories>
                <category name="AAA" />
                <category name="BBB" />
              </categories>
              <properties>
                <property name="CCC" />
                <property name="DDD" />
              </properties>
              <results>
                <test-case name="EEE" />
                <test-case name="DDD" />
               </results>
            </test-suite>
          </results>
        </test-suite>
    </results>
  </test-suite>
</test-A>

【问题讨论】:

  • 您能告诉我们您当前用来查找所需元素的 XPath 表达式吗?似乎test-suite[type="Fixture"] 应该可以解决问题,但我觉得还有一些您没有在问题中说明的进一步要求。
  • 尝试了几个:'*/test-suite[type="Fixture"]' 'test-suite[type="Fixture"]' 更多...

标签: xml perl treenode xml-libxml


【解决方案1】:

查看XPath Examples,了解有关如何创建 xpath 的一些快速提示。

为了指定你想要一个特定的属性,不要忘记@ 符号://test-suite[@type="Fixture"]。此外,您当前的 XML 在"Fixture 之后缺少一个结束引号,我将假设这是一个复制/粘贴错误。

use strict;
use warnings;

use XML::LibXML;

my $dom = XML::LibXML->load_xml({IO => \*DATA});

for my $node ($dom->findnodes('//test-suite[@type="Fixture"]')) {
    print $node, "\n";
}


__DATA__
<test-A>
  <test-suite type="Project">
    <results>
        <test-suite type="Setup">
          <results>
            <test-suite type="Fixture">
              <categories>
                <category name="AAA" />
                <category name="BBB" />
              </categories>
              <properties>
                <property name="CCC" />
                <property name="DDD" />
              </properties>
              <results>
                <test-case name="EEE" />
                <test-case name="DDD" />
               </results>
            </test-suite>
          </results>
        </test-suite>
    </results>
  </test-suite>
</test-A>

【讨论】:

  • 谢谢,XPath 表达式对我有用(我忘了 @ 符号)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 2013-03-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多