按照架构的要求在 XML 中的特定位置插入标签

发布于 2024-10-08 12:10:01 字数 908 浏览 0 评论 0原文

我正在开发一个 JAVA 项目,其中第三方提供了严格的 XSD。 XSD 包含以下构造:

<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>

元素必须按照 XSD 的顺序排列。但所有元素都不是强制性的,因此它们可以在消息中缺失。这里的列表经过简化,实际上要长得多。

如果我想检查 element3 是否存在于传入消息中,如果不存在,则应采取什么方法将其插入消息中的正确位置。我必须考虑所有前面的元素都不存在,因此我不能依赖 element2 的存在并将标签插入到它后面。例如:

<parent>
    <element2/>
</parent>

应该成为

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

我唯一的解决方案是一个复杂的解决方案,我必须搜索 element3 之前的所有元素的存在(从最近的开始)。如果找到前面的元素,我将插入到它后面。如果没有找到,我将插入到父级中。我需要将前面的元素存储在某处(配置或硬编码)。这似乎不是一个优雅的解决方案。

在 Java 中执行此操作的最佳方法是什么?通过代码或使用 XSLT。

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

<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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一梦等七年七年为一梦 2024-10-15 12:10:01

我建议您使用 JAXBXmlBeans 为此。给定一个模式,JAXB 编译器会生成相应的 java 代码,供您解析 XML 或创建它。

我已经成功地将 XmlBeans 用于此类用例,它专门提供了 API 来查询特定元素、属性等是否存在。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文