簡體   English   中英

當字段是通用字段並且實際字段名稱映射到其他位置時,使用JAXB映射XML?

[英]Mapping XML with JAXB, when the fields are generic, and the actual field names are mapped elsewhere?

在我的java(/ spring / hibernate)Web應用程序中,我正在與XML進行這種競爭(出於示例目的,我已經對其進行了很多簡化-我無法修改XML,因為我是從第三方那里收到的-我只是控制客戶端代碼和客戶端域對象-也沒有XSD或WSDL表示此XML):

<?xml version="1.0" encoding="utf-16"?>
<Records count="22321">
    <Metadata>
        <FieldDefinitions>
            <FieldDefinition id="4444" name="name" />
            <FieldDefinition id="5555" name="hair_color"  />
            <FieldDefinition id="6666" name="shoe_size" />
            <FieldDefinition id="7777" name="last_comment"/>
            <!-- around 100 more of these --> 
        </FieldDefinitions>
    </Metadata>

    <!-- Several complex object we don't care about here --> 

    <Record contentId="88484848475" >
        <Field id="4444" type="9">
            <Reference id="56765">Joe Bloggs</Reference>
        </Field>

        <Field id="5555" type="4">
            <ListValues>
                <ListValue id="290711" displayName="Red">Red</ListValue>
            </ListValues>
        </Field>

        <Field id="6666" type="4">
            <ListValues>
                <ListValue id="24325" displayName="10">10</ListValue>
            </ListValues>
        </Field>

        <Field id="7777" type="1">
            &lt;P&gt;long form text here with escaped XML here too
            don't need to process or derefernce the xml here, 
            just need to get it as string in my pojo&lt;P&gt;
        </Field>
    </Record>
    <Record><!-- another record obj here with same fields --> </Record>
    <Record><!-- another record obj here with same fields--> </Record>
    <!-- thousands more records in the sameish format --> 
</Records>

XML包含一個“ records”元素,其中包含一些元數據,然后是許多“ record”元素。 每個記錄元素包含許多“字段”條目。

我的目標是使用JAXB將XML編組為大量的“記錄”對象。 所以我可以做這樣的事情:

List<Record> unmarhsalledRecords = this.getRecordsFromXML(stringOfXmlShownAbove)

每個記錄如下所示:

public class Record {
    private String name;
    private String hairColor;
    private String shoeSize;
    private String lastComment; 
    //lots more fields
    //getters and setters for these fields 
}

但是,我從來不需要在jaxb中解引用字段名-甚至可以用jaxb-或者我是否需要編寫一些凌亂/難以維護的帶有stax解析器的代碼?

在所有此類示例中,我都找不到在線接觸的示例-任何幫助將不勝感激。

謝謝!

我不認為jaxb支持類似復雜的映射邏輯。 我可以想到的幾個選擇。

  1. 使用freemarker或xslt(我討厭xslt)將xml轉換為與所需模型匹配的xml格式,然后再用jaxb進行解析

例如

<Records>
    <Record>
        <Name>Joe Bloggs</Name>
        <HairColour>Red</HairColour>
        ...
    </Record>
</Records>
  1. 照原樣解析xml,並在java層中編寫一個適配器包裝,該包裝將從入站jaxb對象適應到您的“用戶友好”模型。 適配器層可以調用內部的jaxb對象,因此您以后可以在更改后序列化回xml

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM