java - 使用 JDOM API 读取 xml 文件

标签 java xml jdom

<ApiModeling>
  <Flow name="PreFlow">
    <ApiName name="/user/employeeExist/1" value="25182ab0-dd35-4e1b-ac1c-a56bece15119;1.0">
      <Request />
      <Response />
    </ApiName>
   <ApiName name="api1" value="api1Value">
      <Request />
      <Response />
    </ApiName>
  </Flow>
  <Flow name="MainFlow">
    <ApiName name="user/employee/1" value="12dfwcjgs-sjvndjsf">
      <Request />
      <Response />
    </ApiName>
   <ApiName name="api1" value="api1Value">
      <Request />
      <Response />
    </ApiName>
  </Flow>
  <Flow name="PostFlow">
    <ApiName name="api1" value="api1Value">
      <Request />
      <Response />
    </ApiName>
    <ApiName name="api2" value="api2Value">
      <Request />
      <Response />
    </ApiName>
    <ApiName name="api3" value="api3Value">
      <Request />
      <Response />
    </ApiName>
    <ApiName name="api4" value="api4Value">
      <Request />
      <Response />
    </ApiName>
    <ApiName name="api5" value="api5Value">
      <Request />
      <Response />
    </ApiName>
    <ApiName name="api6" value="api6Value">
      <Request />
      <Response />
    </ApiName>
    <ApiName name="api7" value="api7Value">
      <Request />
      <Response />
    </ApiName>
  </Flow>
</ApiModeling>

我能够获得总流量为 3。但是我无法获得元素 ApiName 及其子元素的所有请求响应。

这就是我正在尝试的方法。

 SAXBuilder builder = new SAXBuilder();
          File xmlFile = new File("flowmodeling.xml");
          Document document = (Document) builder.build(xmlFile);
          Element e = document.getRootElement();
          List songElements = document.getRootElement().getChildren("Flow");    

我想获得 ApiName 及其子项的所有请求响应。

请帮帮我

最佳答案

您只需迭代列表 SongElements 即可检索所有元素,例如:

    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File("flowmodeling.xml");
    Document document = (Document) builder.build(xmlFile);
    Element e = document.getRootElement();
    List<Element> songElements = document.getRootElement().getChildren("Flow"); 

    for(Element element : songElements) {
        Element apiName =  element.getChild("ApiName");
        System.out.println(apiName.getAttribute("name"));

        Element request = apiName.getChild("Request");
        System.out.println(request.getValue());

        Element response = apiName.getChild("Response");
        System.out.println(response.getValue());
    }

希望有帮助。

关于java - 使用 JDOM API 读取 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24034894/

相关文章:

java - 在 Java 中解析 XML 文件

php - 如何防止 DOMDocument 将 < 保存为 &lt

java - 如何将文档对象转换为输入源?

java - 无法使用 JDOM 从 XML 获取子属性

java - 将新元素合并到 xml 文件并按年份分组

java - 在使用 hibernate 映射的表中添加列,而不会丢失现有数据

java - 使用Java进行XML解析: <element name ="doctype">

java - HashTagHelper Creator() 具有私有(private)访问权限吗?

c# - XML 反序列化忽略不按字母顺序排列的属性

java - 我无法理解收到的错误