【问题标题】:conversation tree xml representation as java objects对话树 xml 表示为 java 对象
【发布时间】:2011-11-09 16:36:46
【问题描述】:

我有一个关于将对话树映射到 java 对象的推荐方法的问题。我正在查看类似以下内容:

<conversation>
    <npcAction id="1" text="Some action text" userChoice="2" />
    <userChoice id="2">
        <availableAction>3</availableAction>
        <availableAction>4</availableAction>
    </userChocie>
    <userAction id="3" text="Some more action text." npcChoice="5" />
    <userAction id="4" text="Different action text." npcChoice="5" />
    <npcChoice id="5">
        <availableAction>6</availableAction>
        <availableAction>7</availableAction>
    </npcChoice>
    <npcAction id="6" text="Still more action text." userChoice="8" />
    <npcAction id="7" text="Still more action text." userChoice="8" />
    <userChoice id="8" />
</conversation>

然而,当我想象我想如何以编程方式与之交互时,我觉得我想做这样的事情:

public class UserAction {
    String text;
    NpcChoice npcChoice;
}
public class NpcAction {
    String text;
    UserChoice userChoice;
}
public class UserChoice {
    ArrayList<UserAction> actions;
}
public class NpcChoice {
    ArrayList<NpcAction> actions;
}

在实现中,NpcAction 和 UserAction 有其他特定的值来区分它们,但为了简单起见,我将它们删减了。

我的问题是是否有一种简单的方法可以将这些表示绑定在一起。我可以对 xml 数据进行一些中间对象表示,然后在 Java 中手动重新映射它,但我有这种感觉,我错过了表示这些信息的最佳方式的一些东西。任何建议将不胜感激!

【问题讨论】:

    标签: java xml graph tree jaxb


    【解决方案1】:

    您可以执行以下操作:

    用户操作

    public class UserAction {
        @XmlID 
        @XmlAttribute
        String id;
    
        @XmlAttribute String text;
        @XmlIDREF NpcChoice npcChoice;
    }
    

    NpcAction

    public class NpcAction {
        @XmlID 
        @XmlAttribute
        String id;
    
        String text;
        UserChoice userChoice;
    }
    

    用户选择

    public class UserChoice {
        @XmlID 
        @XmlAttribute
        String id;
    
        @XmlElement(name="availableAction")
        ArrayList<UserAction> actions;
    }
    

    NpcChoice

    public class NpcChoice {
        @XmlID 
        @XmlAttribute
        String id;
    
        @XmlElement(name="availableAction")
        ArrayList<NpcAction> actions;
    }
    

    更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-02
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多