Java 将递归XML转换为POJO并返回
我的Java 将递归XML转换为POJO并返回,java,xml,jaxb,pojo,Java,Xml,Jaxb,Pojo,我的XML是这样的: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Trees> <Tree Id="1" Name="FirstTree" Type="Main Tree"> <Description>Main Tree</Description> <Versions > <Versio
XML
是这样的:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Trees>
<Tree Id="1" Name="FirstTree" Type="Main Tree">
<Description>Main Tree</Description>
<Versions >
<Version Id="20592" RootNodeId="117341" CreateDate="2018-01-17 17:01:38 Europe/Moscow" Status="EDIT" Label="TestTree">
<Switch Id="117341" DisplayName="root structure"/>
<Switch Id="117342" DisplayName="root structure">
<ScalarCase Id="40808"/>
<Switch Id="117343" DisplayName="root structure">
<ScalarCase Id="40809"/>
<Switch Id="117344" DisplayName="root structure">
<ScalarCase Id="40810"/>
<Leaf Id="117345"/>
<Condition Id="117346">
<Leaf Id="117347"/>
</Condition>
</Switch>
</Switch>
</Switch>
</<Version>
</Versions>
</Tree>
</Trees>
主树
假设您已经创建了镜像xml的POJO,从:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="Trees")
public class Trees {
private Tree Tree;
// getters and setters
}
要切换类(其余我将不在这里写):
你所有的POJO都要有适当的注解等等
然后尝试将xml读入POJO,似乎可以:
public static void main(String[] args) {
try {
File file = new File("trees.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Trees.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Trees trees = (Trees) jaxbUnmarshaller.unmarshal(file);
System.out.println(trees);
} catch (JAXBException e) {
e.printStackTrace();
}
}
编辑:
也可以在回答部分回复评论
当一个类包含一个字段并将其自身作为一个类型时,它实际上会创建一个LinkedList,这样您就可以拥有所需的任何深度(在内存限制内)。假设您已经创建了镜像xml的POJO,从:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="Trees")
public class Trees {
private Tree Tree;
// getters and setters
}
要切换类(其余我将不在这里写):
你所有的POJO都要有适当的注解等等
然后尝试将xml读入POJO,似乎可以:
public static void main(String[] args) {
try {
File file = new File("trees.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Trees.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Trees trees = (Trees) jaxbUnmarshaller.unmarshal(file);
System.out.println(trees);
} catch (JAXBException e) {
e.printStackTrace();
}
}
编辑:
也可以在回答部分回复评论
当一个类包含一个自身作为类型的字段时,它本质上会创建一个LinkedList,这样您就可以拥有所需的任何深度(在内存限制内)。困难在于Switch和Condition对象可以包含任何深度的其他对象。在您的示例中,只能有一个嵌套对象。我认为Switch可以包含任意深度的Switch对象,请尝试在xml中放置多个级别的Switch,看看它是否有效。困难在于Switch和Condition对象可以包含任意深度的其他对象。在您的示例中,只能有一个嵌套对象。我相信Switch可以包含任意深度的Switch对象,请尝试在xml中放置多个级别的Switch,看看它是否有效