Best way to match Attribute value in XML element

坚强是说给别人听的谎言 提交于 2019-12-13 18:07:03

问题


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");
}


来源:https://stackoverflow.com/questions/22683721/best-way-to-match-attribute-value-in-xml-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!