Java 删除 ns2 作为默认命名空间前缀

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16589600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 12:19:56  来源:igfitidea点击:

Remove ns2 as default namespace prefix

javaxmljaxb

提问by Vegard

I have a file that is printed with a default namespace. The elements are printed with a prefix of ns2, I need this to be removed, how it is with my code:

我有一个使用默认命名空间打印的文件。元素以 ns2 的前缀打印,我需要删除它,我的代码如何:

<ns2:foo xmlns:ns2="http://namespace" />

how I want it to be:

我希望它如何:

<foo xmlns="http://namespace" />

this is how I have coded it, something which as I see it should be enough for the ns2 to go away:

这就是我编码它的方式,在我看来,它应该足以让 ns2 消失:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:bar="http://namespace" targetNamespace="http://namespace"
    elementFormDefault="qualified">
...

the generated package-info turns out like this:

生成的包信息结果是这样的:

@javax.xml.bind.annotation.XmlSchema(namespace = "http://namespace", 
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.foo.bar;

I create the file like this:

我创建这样的文件:

JAXBContext jaxbContext = JAXBContext.newInstance(generatedClassesPackage);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(new JAXBElement<Foo>(new QName("http://namespace", "Foo"),
Foo.class, rootFoo), outputStream);

generatedClassesPackage is the package where package-info.java and the elements are.

generateClassesPackage 是 package-info.java 和元素所在的包。

The Foo object is defined and has elements like this::

定义了 Foo 对象并具有如下元素:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "group"
})
@XmlRootElement(name = "Foo")
public class Foo {

    @XmlElement(name = "Group", required = true)
    protected List<Group> group;

Is it something I have missed? or have I misunderstood how this works?

是我错过了什么吗?还是我误解了这是如何工作的?

采纳答案by Daniel Moses

Most likely you have multiple namespaces in the response. This will use the default convention of creating ns# namespace prefixes and one of them becomes the xmlns without a prefix. If you want to control this you can do the following:

很可能您在响应中有多个命名空间。这将使用创建 ns# 命名空间前缀的默认约定,其中之一成为没有前缀的 xmlns。如果您想控制它,您可以执行以下操作:

NamespacePrefixMapper mapper = new NamespacePrefixMapper() {
        public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
            if ("http://namespace".equals(namespaceUri) && !requirePrefix)
                return "";
            return "ns";
        }
    };
    marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", mapper);
    marshaller.mashal....

This will set the http://namespaceas the default xmlns always and use ns# for all other namespaces when marshalling. You can also give them more descriptive prefixes if you want.

这将http://namespace始终将xmlns设置为默认值,并在编组时将 ns# 用于所有其他命名空间。如果需要,您还可以为它们提供更多描述性前缀。

回答by s332401890

Beginning from JDK6u18 the NamespacePrefixMapper technique is not used anymore.

从 JDK6u18 开始,不再使用 NamespacePrefixMapper 技术。

回答by yonia

All you need 2 do is when you open a new package select create package info in the package info add the following annotation or change it as needed

您需要做的就是当您打开一个新包时,在包信息中选择创建包信息添加以下注释或根据需要进行更改

@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.sitemaps.org/schemas/sitemap/0.9", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED, xmlns = { @javax.xml.bind.annotation.XmlNs(namespaceURI = "http://www.sitemaps.org/schemas/sitemap/0.9", prefix = "") })

This will remove the ns2 prefix

这将删除 ns2 前缀

回答by Diego Maye

I solve this deleting the file package-info.java into the jaxb classes package and re-compiling the application.

我解决了这个问题,将文件 package-info.java 删除到 jaxb classes 包中并重新编译应用程序。

回答by Vladimir

For Java 8:

对于 Java 8:

I chagnge prefix name from 'ns2' to 'fault'.

我将前缀名称从“ ns2”更改为“ fault”。

Firstly, create your *DefaultNamespacePrefixMapper *.

首先,创建您的 *DefaultNamespacePrefixMapper *。

import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
import java.util.HashMap;
import java.util.Map;

public class DefaultNamespacePrefixMapper extends NamespacePrefixMapper {

    private static final String FAULT_PREFIX = "fault";

    private Map<String, String> namespaceMap = new HashMap<>();

    public DefaultNamespacePrefixMapper() {
        this.namespaceMap.put(NAMESPACE, FAULT_PREFIX);
    }

    @Override
    public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
        return namespaceMap.getOrDefault(namespaceUri, suggestion);
    }
}

Secondy, add your DefaultNamespacePrefixMapperto Marshaller property.

其次,将您的DefaultNamespacePrefixMapper添加到 Marshaller 属性。

@SuppressWarnings("unchecked")
private <T> void returnFault(T fault, SoapFault soapFault) {
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(fault.getClass());
        QName name = new QName(NAMESPACE, fault.getClass().getSimpleName());
        JAXBElement<T> element = new JAXBElement<>(name, (Class<T>) fault.getClass(), fault);

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new DefaultNamespacePrefixMapper());
        marshaller.marshal(element, soapFault.addFaultDetail().getResult());
    } catch (JAXBException e) {
        log.error("Exception when marshalling SOAP fault.", e);
    }
}

Thirdly, add following dependencies in gradle/maven.

第三,在 gradle/maven 中添加以下依赖项。

compile 'com.sun.xml.bind:jaxb-impl:2.2.11'
compile 'com.sun.xml.bind:jaxb-core:2.2.11'

回答by Boss

Change the attribute value of elementFormDefault="unqualified" in

更改 elementFormDefault="unqualified" 中的属性值

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:bar="http://namespace" targetNamespace="http://namespace" elementFormDefault="qualified">