开发者

Inserting a tag in XML at a specific position as mandated by schema

I'm working on a JAVA project where a strict XSD has been provided by a 3rd party. The XSD contains the following constructs:

&开发者_如何学运维lt;sequence>
    <element name="element1" type="type1" nillable="true" minOccurs="0"/>
    <element name="element2" type="type2" nillable="true" minOccurs="0"/>
    <element name="element3" type="type3" nillable="true" minOccurs="0"/>
</sequence>

The elements have to be in this order according to the XSD. But all elements are not mandatory so they can be absent in the message. The list here is simplified and is actually much longer.

What approach should I take if I want to check that element3 is present in an incoming message and if it is not present insert it at the correct position in the message. I have to consider the absence of all preceding elements so I cannot rely on the presence of element2 for example and insert the tag behind it. For example:

<parent>
    <element2/>
</parent>

Should become

<parent>
    <element2/>
    <element3/>
</parent>

The only solution I have is a complicated one where I have to search for the presence of all elements preceding element3 (starting with the nearest). If a preceding element is found I insert behind it. If none is found I insert into the parent. I need to store the preceding elements somewhere (config or hardcoded). This does not seem an elegant solution.

What is the best way to do this in Java? Either in code or using an XSLT.


I suggest you use JAXB or XmlBeans for this. Given a schema, the JAXB compiler generates corresponding java code for you to work with either parsing the XML or creating it.

I have been successfully using XmlBeans for these kind of use cases and it specifically provides the API to query for the presence of a particular element, attribute etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜