Best way to match Attribute value in XML element

2019-08-15 08:57发布

问题:

My XML:

< measValue dn="Cabinet=0, Shelf=0, Card=2, Host=0">

    < r p="1">1.42</r>

    < r p="2">2.28</r>

< /measValue>

I want to match getAttribute("dn") with different patterns like

1> Host=0 # this is very easy

my solution:

if (getAttribute("dn")=~ /Host=0/)

2> Host=0 && Card=2

I can do it but I need to match it twice like

if (getAttribute("dn")=~ /Host=0/) && (getAttribute("dn")=~ /Card=2/)

Is there any better way to accomplice this match this second pattern? using LibXML

回答1:

Have a try with:

if (getAttribute("dn")=~ /^(?=.*\bHost=0\b)(?=.*\bCard=2\b)/)

The word boundaries \b are here to avoid matching myHost=01 and everything similar.



回答2:

Your approach has the problem that getAttribute("dn") =~ /Card=2/ would also match a value of Card=25 which is probably not what you want.

I would first write a helper that converts a string with key/value pairs into a hash:

sub key_value_pairs_to_hash {
    my $string = shift;
    my %hash;

    for my $pair (split(/\s*,\s*/, $string)) {
        my ($key, $value) = split(/\s*=\s*/, $pair, 2);
        $hash{$key} = $value;
    }

    return \%hash;
}

Then you can test the values like this:

my $hash = key_value_pairs_to_hash('Cabinet=0, Shelf=0, Card=2, Host=0');

if ($hash->{Host} == 0 && $hash->{Card} == 2) {
    print("match\n");
}