gpt4 book ai didi

java - JAXB 多行属性

转载 作者:行者123 更新时间:2023-11-30 07:11:42 25 4
gpt4 key购买 nike

有没有办法编码/解码 xml/对象多行属性。

目前显示为

<task name="Payament Gateway
Checker" >

如果通过用\n 替换下一行空格来存储它会是最好的?

<task name="Payament Gateway \n Checker" >

编辑 -

尝试了 Adapter 和 JaxbListener - 但转换为 name="Payment Gateway Checker"

void beforeMarshal(Marshaller marshaller) {
name = name.replaceAll("\n", "&#xA;");
}

@XmlJavaTypeAdapter(MultilineString.class)
@XmlAttribute
protected String name;

public class MultilineString extends XmlAdapter<String, String> {
@Override
public String marshal(String input) throws Exception {
return input.replaceAll("\n", "&#xA;");
}
@Override
public String unmarshal(String output) throws Exception {
return output;
}
}

最佳答案

长话短说

JAXB 应该将 Java \n 替换为 ,这是正确的 XML 转义。如果您没有看到这一点,那么您正在使用的 JAXB 实现版本可能存在错误。例如,此问题已在 EclipseLink JAXB (MOXy) 中修复在版本 2.5.1 中:


例子

Java 模型(Foo)

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Foo {

private String bar;

@XmlAttribute
public String getBar() {
return bar;
}

public void setBar(String bar) {
this.bar = bar;
}

}

演示代码

import javax.xml.bind.*;

public class Demo {

public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Foo.class);

Foo foo = new Foo();
foo.setBar("Hello\nWorld");

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(foo, System.out);
}

}

输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo bar="Hello&#xA;World"/>

解决方法

您始终可以使用 XmlAdapter 来控制 JAXB 中的任何输出。

关于java - JAXB 多行属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20896645/

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