سؤال

I have this xml file, I need to get the categories, properties and test-case, I successfully done it using XML::LibXML and findnodes The problem is the sometimes the structure is different so there may be some more test-suite & results nodes then the node in the findnodes is not correct.

So what is the best way to handle it ? Not sure how to search for type="Fixture ( which is the node that has the info I need ) if I don't know the correct base starting node.

<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>
هل كانت مفيدة؟

المحلول

Take a look at XPath Examples for some quick tips on how to create xpaths.

In order to specify that you want a specific attribute, don't forget the @ symbol: //test-suite[@type="Fixture"]. Also, your current XML is missing a closing quote after "Fixture which I'm going to assume is a copy/paste error.

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>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top