0

特定の値を置き換えたい (すべての要素ではありません)。ここではすべて同じ Background_color を使用していますが、Background_color を特定のものだけに置き換えたくありません。どのように実装できますか?これは単なるサンプル コードです (Background_color を置き換えてはならないスキン名のリストがファイルに含まれています)。

            <Skins>
             <skin>
               <att name="Name" value="sknLblG3S3" type="String"/>
               <att name="WidgetType" value="Label" type="String"/>
               <att name="Background_color" value="228,221,213" type="RGB"/>
            <skin>
            <skin>
              <att name="Name" value="name" type="String"/>
              <att name="WidgetType" value="Label" type="String"/>
              <att name="Background_color" value="228,221,213" type="RGB"/>
            <skin>
            <skin>
              <att name="Name" value="sknLblG3S5" type="String"/>
              <att name="WidgetType" value="Label" type="String"/>
              <att name="Background_color" value="228,221,213" type="RGB"/>
            <skin>
            <skins>
4

2 に答える 2

1

あなたの XML が実際に有効であると仮定すると (あなたのサンプルはそうではありません - タグのいくつかを手動で修正する必要がありました)、XML パーサーを使用する必要があります。perlにタグを付けたので、perlの回答が受け入れられると思います:

#!/usr/bin/env perl
use strict;
use warnings;
use XML::Twig;

my $twig = XML::Twig->parsefile( 'your_file.xml' );

#find and iterate all the 'skin' elements. 
foreach my $skin ( $twig->get_xpath('//skin') ) {
    #Check the 'att' element with these particular attributes. E.g. Name, sknLblG3S3
    if ( $skin->get_xpath('./att[@name="Name"][@value="sknLblG3S3"]') ) {
        #select the att with a name of 'Background_Colour' 
        my $bg_att = $skin->get_xpath( './att[@name="Background_color"]', 0 );
        #modify the attribute 'value'. 
        $bg_att->set_att( 'value', "123,456,789" );
    }
}

#set output formatting - note, this can break with certain XML elements, which you don't seem to have. 
$twig->set_pretty_print('indented');
$twig->print;

XML::Twig のメソッドは属性を読み取りattます$skin -> children()。ただし、この例ではより明確attに感じます。xpath

(おそらく、より複雑な xpath ステートメントを実行して、子供/兄弟を一致させることもできますが、それが読みやすさに役立つかどうかはわかりません)。

于 2015-11-19T11:44:43.487 に答える