gpt4 book ai didi

java - XStream 的命名空间限定属性

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:15:26 25 4
gpt4 key购买 nike

我正在使用 XStream 从几个 Java 类生成 XML,我需要为某些元素指定命名空间限定的属性;即 xml:id 和 xlink:href 属性。

我正在使用 StaxDriver,我可以使用 QNameMap 为元素配置命名空间,它只是属性的命名空间,我还没有找到解决方案。

本质上,我有一个类

@XStreamAlias("someElement")
public class SomeElement
{
@XStreamAsAttribute
String id = "foo";
@XStreamAsAttribute
String href = "http://bar"
}

我需要将其序列化为:

<someElement xml:id="foo" xlink:href="http://bar"/>

使事情复杂化的是,我不能假设任何名为“id”的属性都应该变成“xml:id”,或者任何名为“href”的属性都应该变成“xlink:href”。

最佳答案

经过更多的谷歌搜索,我想我找到了答案,而且解决方案比我想象的要简单。

我太聪明了,正在寻找使某些组件“识别命名空间”的方法,这是一场失败的战斗。我找到的解决方案是忘记 StaxDriver 和 QNameMaps 并简单地使用 @XStreamAsAttribute 和 @XStreamAlias 按摩字段以生成所需的命名空间属性。即

@XStreamAlias("root")
class RootElement
{
@XStreamAsAttribute
final String xmlns = "http://www.example.org"

@XStreamAsAttribute
@XStreamAlias("xmlns:xlink")
final String xlink="http://www.w3.org/1999/xlink"

SomeElement someElement
}

class SomeElement
{
@XStreamAsAttribute
@XStreamAlias("xml:id")
String id

@XStreamAsAttribute
@XStreamAlias("xlink:href")
String href
}

通过上面我得到了想要的 XML:

<root xmlns="http://www.example.org" xmlns:xlink="http://www.w3.org/1999/xlink">
<someElement xml:id="p1" xlink:href="http://www.example.org"/>
</root>

这可能不是最好的或适当的方法,但它可以满足我现在的需要。

关于java - XStream 的命名空间限定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8335970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com