问题
Here is the XML I have (ish)
<?xml version="1.0" encoding="UTF-8"?>
<edi837>
<ISA >
<ISA01>00</ISA01>
<ISA02> </ISA02>
<GS>
<GS01>HC</GS01>
<GS07>X</GS07>
<GS08>005010X223A2</GS08>
<ST>
<ST01>837</ST01>
<ST02>0001</ST02>
<ST03>005010X223A2</ST03>
<BHT>
<BHT01>19</BHT01>
<BHT02>0</BHT02>
<BHT03>524</BHT03>
<BHT04>20111207</BHT04>
<BHT05>1323</BHT05>
<BHT06>CH</BHT06>
</BHT>
<Loop1000/>
<Loop1000/>
<Loop2000/>
<Loop2000/>
</ST>
</GS>
</ISA>
</edi837>
<-- However, I have: -->
<?xml version="1.0" encoding="UTF-8"?>
<edi835>
<ISA>
<ISA01>00</ISA01>
<ISA02>Authorizat</ISA02>
<ISA16/>
<GS>
<GS06>1</GS06>
<GS07>X</GS07>
<GS08>005010X221A1</GS08>
<ST>
<ST01>835</ST01>
<ST02>0001</ST02>
<BPR/>
<TRN/>
<DTM/>
<Loop1000A/>
<Loop1000B/>
<Loop2000/>
<PLB/>
</ST>
<ST>
<ST01>835</ST01>
<ST02>0001</ST02>
<BPR/>
<TRN/>
<DTM/>
<Loop1000A/>
<Loop1000B/>
<Loop2000/>
<PLB/>
</ST>
</GS>
</ISA>
</edi835>
My basic problem is that, I have a field in a parent element that tells me what the subtype is up the child field
<GS08>005010X223A2</GS08>
What's the correct way to do this?
I Basically Want a XmlTypeAdapter that can take me from 1 bound-type to another. Like: "Give me the first elements and I will tell you what to do with the rest of them" An object factory might be able to do this. Hope this is clear
Each <ST> structure can be so radically different that really, what I want to do is just specify up until that <ST> and then let it reflect the rest of the types from there.
I have completely replaced the original, contrived XML with ACTUAL XML (condensed). I solved it here but it's ugly
回答1:
Don't Do It
My basic problem is that, I have a field in a parent element that tells me what the subtype is up the child field (qualifier). What's the correct way to do this?
I wouldn't do it this way since it doesn't correspond to a standard way of representing inheritance in XML. This means that you will have to jump through hoops to process it, as will everyone else that needs to interact with this XML.
What to Do Instead
Drop the qualifier element and keep everything else the same. This makes the subtypes the element name the qualifier. This corresponds to the XML Schema concept of substitution groups, and is a standard way of representing inheritance. It also makes your XML a bit shorter which is a good thing.
Java Model
Inner
You will use the @XmlElementRef annotation on the problemType field/property on the Inner class. The type to be unmarshalled will be based element encountered, and which subtype has a matching @XmlRootElement annotation.
@XmlAccessorType(XmlAccessType.FIELD)
public class Inner {
@XmlElementRef
private ProblemType problemType;
}
ProblemType1
@XmlRootElement(name="ProblemType1")
public class ProblemType1 extends ProblemType {
}
ProblemType2
@XmlRootElement(name="ProblemType2")
public class ProblemType2 extends ProblemType {
}
来源:https://stackoverflow.com/questions/28185692/how-to-choose-a-specific-subtype-to-bind-to-based-on-qualifiers