在编组jaxb时从根元素中删除xmlns属性 [英] remove xmlns attribute from the root element while marshalling jaxb
问题描述
这可能与 JAXB Marshaller有关 - 如何做我压制xmlns命名空间属性?
但我的问题有点不同。
我做常规java编组,我的xsd没有名称空间。生成的xml也没有名称空间,除了根元素。
But my problem is a little different. I do the regular java marshalling and my xsd has no namespaces.The generated xml is without namespaces as well, except for the root element.
<?xml version="1.0" encoding="UTF-8"?><rootElement xmlns:ns2="unwanted namespace">
不受欢迎的命名空间
来自另一个模式同一个项目,我不知道为什么会在这个阶段被选中。
The unwanted namespace
is from another schema from the same project and I am not sure why that is being picked up at this stage.
我的rootElement.java由jaxb2-maven-plugin生成如下:
My rootElement.java generated by jaxb2-maven-plugin looks like :
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"feed"
})
@XmlRootElement(name = "rootElement", namespace = "")
public class RootElement{
....
}
此时我只想摆脱 xmlns:ns2 =unwanted namespace来自生成的xml的
属性,我正在努力解决它。
At this point all I want is to get rid of the xmlns:ns2="unwanted namespace"
attribute from the generated xml and I am struggling with it.
我查看了我的package-info.java,看起来像:
I looked at my package-info.java and it looks like:
@javax.xml.bind.annotation.XmlSchema(namespace = "unwanted namespace", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.mypackage;
我尝试添加 -npa
但它出于某种原因,不能使用 jaxb2-maven-plugin
。我尝试了 NamespaceMapper
,但这适用于更改前缀。我无法完全删除命名空间。这让我困扰了一天。
I tried adding he -npa
but it wont work on jaxb2-maven-plugin
for some reason. I tried the NamespaceMapper
but that works for changing prefixes. I could not get it to remove the namespace altogether. This is bothering me for a day now.
推荐答案
我目前有类似的要求。对我有用的唯一解决方案是为XMLStreamWriter实现一个包装器。
I have similar requirements at the moment. The only solution that worked for me is implementing a wrapper for XMLStreamWriter.
请在此处查看我的回答。我还描述了我尝试过的其他解决方案。
Please, take a look at my answer here. I've also described there other solutions I tried out.
使用上面链接中的代码进行序列化如下所示:
Serialization using code from the link above looks like this:
XMLOutputFactory factory = XMLOutputFactory.newFactory();
StringWriter writer = new StringWriter(XML_BUFFER_INITIAL_SIZE);
XMLStreamWriter xmlWriter = null;
try {
xmlWriter = factory.createXMLStreamWriter(writer);
JAXBContext context = JAXBContext.newInstance(MyJAXBGeneratedClass.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(reportContainer, new NamespaceStrippingXMLStreamWriter(xmlWriter));
xmlWriter.flush();
}
finally {
if (xmlWriter != null)
xmlWriter.close();
}
return writer.toString();
这篇关于在编组jaxb时从根元素中删除xmlns属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!