Keep child-parent relationship after unmarshalling

2019-03-06 07:06发布

Here is an example of what I'm trying to unmarshall with JAXB:

<?xml version="1.0" encoding="UTF-8"?>
<menus>
    <menu>
        <name>main</name>
        <subMenu>
            <name>mainMenu</name>
            <!-- Transfer / Versement -->
            <subMenu>
                <name>transfer</name>
                <label>MENU_TRANSFER</label>
                <icon>call-received</icon>

                <menuItem>
                    <name>record</name>
                    <label>MENU_RECORD</label>
                    <url>/pages/record/search/recordListSearchResult.jsf</url>
                </menuItem>

                <menuItem>
                    <name>transferInput</name>
                    <label>MENU_TRANSFER_OPEN</label>
                    <url>/pages/transfer/open/transferListOpen.jsf</url>
                </menuItem>
        </subMenu>
    </menu>
</menus>

Once unmarshalled, with java generated code, I want to be able to retrieve the submenu parent of a menuItem (without having to use loop etc.) Basically, I want to generate a getter getParent on MenuItem returning his parent. Is there an easy way to do this?

标签: jaxb
1条回答
该账号已被封号
2楼-- · 2019-03-06 07:27

You can use Unmarshal Event Callbacks to receive parent object in the instance of your mapped class after unmarshalling. To do this simply add a method with the following signature:

void afterUnmarshal(Unmarshaller unmarshaller, Object parent);

Thus you'll get the parent submenu in the child submenu after unmarshalling.

If your mapped classes are schema-derived (for example you compile some XML schema with XJC), you can use the code injector plugin to add code to generated classes.

I also think there should be XJC plugins for handling parent objects (google XJC or JAXB parent plugin).

查看更多
登录 后发表回答