4

これは初心者の質問に違いありませんが、http: //x-stream.github.io/からは取得できませんでした。

さて、私は次のxml文字列を持っています

<cat age="4" >
   <name>Garfield</name>
</cat>

次の場所にマッピングする必要があります。

class Cat {
  int age;
  String name;
}

XStreamを使用してそれを行う簡単な方法はありますか?そうでない場合、他に何を試すことができますか?

前もって感謝します。

4

3 に答える 3

3

次のようにクラスに注釈を付けます (詳細については、http: //x-stream.github.io/annotations-tutorial.htmlを確認してください)。

@XStreamAlias("cat")
class Cat {
  @XStreamAsAttribute
  int age;
  String name;
}

XStream を次のように使用します。

xstream = new XStream();
xstream.processAnnotations(Cat.class);
Cat roundtripGarfield = (Cat)xstream.fromXML(xstream.toXML(garfield));
于 2010-02-23T22:52:32.520 に答える
0

実際、XStream サイト (Converter チュートリアル) に回答があります ;)

http://x-stream.github.io/converter-tutorial.htmlから:

    public Object unmarshal(HierarchicalStreamReader reader,
                    UnmarshallingContext context) {
            Birthday birthday = new Birthday();
            if (reader.getAttribute("gender").charAt(0) == 'm') {
                    birthday.setGenderMale();
            } else {
                    birthday.setGenderFemale();
            }
            reader.moveDown();
            Person person = (Person)context.convertAnother(birthday, Person.class);
            birthday.setPerson(person);
            reader.moveUp();
            reader.moveDown();
            Calendar date = (Calendar)context.convertAnother(birthday, Calendar.class);
            birthday.setDate(date);
            reader.moveUp();
            return birthday;
    }

(ページの最後の例/コード ブロックにあります。)

HTH

編集:そのコードブロックを探すだけでなく、そのチュートリアル全体を実行したいことを追加したかっただけです。独自のコンバーターを作成し、それを XStream インスタンスに登録する必要があります。(当たり前のことかもしれませんが、念のため…)

于 2010-02-23T22:11:30.480 に答える
-1

XPath を使用できます。

最新の JVM で非常に高速であり、移転可能なスキルです。たとえば、.NET などで XPath を使用できます。

于 2010-02-23T22:10:29.357 に答える