gpt4 book ai didi

java - 防止 eclipselink moxy 转义元素内容

转载 作者:行者123 更新时间:2023-12-02 04:03:29 31 4
gpt4 key购买 nike

我有以下类(class):

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "item", propOrder = {
"content"
})
public class Item {

@XmlElementRefs({
@XmlElementRef(name = "ruleref", type = JAXBElement.class, required = false),
@XmlElementRef(name = "tag", type = JAXBElement.class, required = false),
@XmlElementRef(name = "one-of", type = JAXBElement.class, required = false),
@XmlElementRef(name = "item", type = JAXBElement.class, required = false)
})
@XmlMixed
protected List<Serializable> content;

元素可以包含带引号的字符串,例如:

<tag>"some kind of text"</tag>

此外,item 元素本身可以包含带引号的字符串:

<item>Some text, "this has string"</item>

使用 Moxy 时生成的 XML 对标记和项目元素中的文本值进行转义:

<tag>&quote;some kind of text&quote;</tag>

我怎样才能阻止它这样做,但仅限于这些元素?属性和其他元素应保持不变(我的意思是转义)。

谢谢。

最佳答案

您可以通过提供自己的 CharacterEscapeHandler 来覆盖默认字符转义。

Java 模型

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Foo {

private String bar;

public String getBar() {
return bar;
}

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

}

演示代码

演示

import java.io.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import org.eclipse.persistence.oxm.CharacterEscapeHandler;

public class Demo {

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

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

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

marshaller.setProperty(MarshallerProperties.CHARACTER_ESCAPE_HANDLER, new CharacterEscapeHandler() {

@Override
public void escape(char[] buffer, int start, int length,
boolean isAttributeValue, Writer out) throws IOException {
out.write(buffer, start, length);
}

});

marshaller.marshal(foo, System.out);
}

}

输出

<?xml version="1.0" encoding="UTF-8"?>
<foo>
<bar>&quot;Hello World&quot;</bar>
</foo>
<?xml version="1.0" encoding="UTF-8"?>
<foo>
<bar>"Hello World"</bar>
</foo>

关于java - 防止 eclipselink moxy 转义元素内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19528943/

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