java - XML 应该属于哪种类型的 Java 数据结构?

标签 java xml

我正在编写一个 Java 程序,它使用 XML 文件作为模板来填充数据结构,然后该程序接受用户输入并与之交互。

我想要的是保持这种层次结构的东西:

  <CYO>
    <node>
      <to>
    home
      </to>
      <message>
    This is the message that will be displayed to the user.
      </message>
      <option>
    <name>
      fun <!-- option that is dispalyed and command to be entered -->
    </name>
    <goto>
      not home <!-- next node to be displayed for this command -->
    </goto>
      </option>
      <option>
    <name>
      no fun
    </name>
    <goto>
      home <!-- should trigger the reprinting of the same message; goto/home = to/home -->
    </goto>
      </option>
    </node>
    <node>
      <to>
    not home
      </to>
      <message>
    Welcome you have just left home.
    What else do you want to do?
      </message>
      <option>
    <name>
      back home
    </name>
    <goto>
      home
    </goto>
      </option>
      <option>
    <name>
      fun
    </name>
    <goto>
      not home <!-- should trigger the reprinting of the same message; goto/not home = to/not home -->
    </goto>
      </option>
    </node>
  </CYO>

在Java中,我一直在尝试对如何从“选项/名称::goto”调用节点项的逻辑进行排序,然后让程序返回与“选项/名称”匹配的“节点/到”::去'。真正的问题是我不确定这需要如何在 Java 中表示,以便正确返回这样的调用。这是我到目前为止在 Java 中所做的:

List<Map<String, Object<String, String>>> CYO =  new ArrayList();

Map<String, Object> home = new HashMap<String, Object>();
home.put("to", "home");
home.put("message", "This is the message that will be displayed to the user.");
Map<String, String> Option1 = new HashMap<String, String>();
Option1.put("fun", "not home");
Option1.put("no fun", "home");

home.put("option", Option1);

Map<String, Object> not_home = new HashMap<String, Object>();
not_home.put("to", "not home");
not_home.put("message", "Welcome you have just left home.\\nWhat else do you want to do?");
not_home.put("option", "not home");
Map<String, String> Option2 = new HashMap<String, String>();
Option2.put("back home", "home");
Option2.put("fun", "not_home");

not_home.put("option", Option2);


CYO.add(home);
CYO.add(not_home);

System.out.println(CYO.indexOf("not_home"));

我从 IDE 收到错误消息:“对象类型不是泛型;它无法使用参数进行参数化。

最佳答案

您的问题有两个部分。

  1. 将 xml 文件/配置读入数据结构(jaxb 会为您完成此操作)。

    • 为此 xml 表示创建一个 xsd,
    • 使用xjc或jaxb生成java代码。
  2. 从 goto 获取引用的节点。

    • 将 xml 文件读取到 java 对象 Cyo。
    • 读取后,将命名节点存储在 hashmap Map 映射 -> HashMap() 中。
    • 遍历到goto时,Node gotoNode = map.get(theNodeName)

    • gotoNode.execute()

关于java - XML 应该属于哪种类型的 Java 数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55930838/

相关文章:

java - 无法与自定义控件 onClick 交互

c# - 如何使用 RestSharp 进行 XmlDeserialize?

Android Studio 在可绘制属性处显示红色感叹号

xml - 如何在 Scala 类中漂亮地表示 XML 实体?

android - 如何在 as3, air for android 中加载 xml

java - 获取 JInternalFrame 出现的问题

java - 当我们有多个 Activity 时如何集中运行时权限

java - OR 条件中的所有 boolean 值是否都在 Java 中求值?

java - "Exception in thread "main "java.lang.NullPointerException"运行网页抓取程序时出错

通过 URLClassLoader 加载的 Java 插件运行后不返回