如果有多个级别的相同 XML 节点,如何遍历 JAXB 类

这是我实际 XML 的最漂亮版本(我没有 XSD,也不会从源系统中获得它)


<?xml version="1.0" encoding="UTF-8"?>

<Root>

  <!--Java Class Comp.java-->

  <Comp>

    <Name>Component Name</Name>

    <Available_Start_Date>2018-07-10</Available_Start_Date>

    <!--Java Class P_to_P.java-->

    <P_to_P>

      <Max>1</Max>

      <Min>1</Min>

      <!-- Java Class P.java-->

      <P>

        <Name>Composite</Name>

        <P_to_P>

          <Max>1</Max>

          <Min>1</Min>

          <P>

            <Name>Another Level</Name>

          </P>

        </P_to_P>

        <P_to_P>

          <Max>1</Max>

          <Min>1</Min>

          <P>

            <Name>Yet Another Level</Name>

          </P>

        </P_to_P>

      </P>

    </P_to_P>

  </Comp>

</Root>

现在,如果我开始为它编写 JAXB 类(手工和使用 IDE),我必须为我正在经历的每个级别编写 for 循环。现在,这个 XML 中的孩子可能会显示为孩子的父母(P_to_P 有 P 作为孩子,P 有 P_to_P 作为孩子,并且父子关系的深度可以是任意数量的级别。

因此,如果我编写一个 Main JAXB 文件,那么我是否必须在 for 循环中编写那么多数量的 for 循环来遍历所有父级和子级?还是有更好的方法来实现它?



犯罪嫌疑人X
浏览 274回答 1
1回答

呼啦一阵风

您可以编写您的 POJO 类P,P_to_P类似于:@XmlAccessorType(XmlAccessType.FIELD)public class P_to_P {&nbsp; &nbsp; @XmlElement(name = "Max")&nbsp; &nbsp; private int max;&nbsp; &nbsp; @XmlElement(name = "Min")&nbsp; &nbsp; private int min;&nbsp; &nbsp; @XmlElement(name = "P")&nbsp; &nbsp; private P p;&nbsp; &nbsp; // public getters and setters (omitted for brevity)}@XmlAccessorType(XmlAccessType.FIELD)public class P {&nbsp; &nbsp; @XmlElement(name = "Name")&nbsp; &nbsp; private String name;&nbsp; &nbsp; @XmlElement(name = "P_to_P")&nbsp; &nbsp; private List<P_to_P> pToPList;&nbsp; &nbsp; // public getters and setters (omitted for brevity)}然后你可以遍历整个树并像下面这样处理每个项目。注意递归:方法process(P_to_P)调用process(P)和方法process(P)调用process(P_to_P)。还要注意null防止NullPointerException和终止递归的检查。public static void main(String[] args) {&nbsp; &nbsp; File file = new File("root.xml");&nbsp; &nbsp; JAXBContext jaxbContext = JAXBContext.newInstance(Root.class);&nbsp; &nbsp; Unmarshaller unmarshaller = jaxbCntext.createUnmarshaller();&nbsp; &nbsp; Root root = (Root) unmarshaller.unmarshal(file);&nbsp; &nbsp; P_to_P pToP = root.getComp().getPToP();&nbsp; &nbsp; process(pToP);}private static void process(P_to_P pToP) {&nbsp; &nbsp;if (pToP == null)&nbsp; &nbsp; &nbsp; &nbsp;return;&nbsp; &nbsp;// do anything you like here&nbsp; &nbsp;process(pToP.getP());}private static void process(P p) {&nbsp; &nbsp;if (p == null)&nbsp; &nbsp; &nbsp; &nbsp;return;&nbsp; &nbsp;// do anything you like here&nbsp; &nbsp;if (p.getpToPList() == null)&nbsp; &nbsp; &nbsp; &nbsp;return;&nbsp; &nbsp;for (P_to_P pToP : p.getpToPList()) {&nbsp; &nbsp; &nbsp; &nbsp;process(pToP);&nbsp; &nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java