删除ns2作为默认名称空间前缀 [英] Remove ns2 as default namespace prefix

查看:125
本文介绍了删除ns2作为默认名称空间前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:foo xmlns:ns2="http://namespace" />

我希望如何:

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

这就是我编码的方式,正如我所看到的那样,ns2应该足够了离开:

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

<?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">
...

生成的包信息如下:

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

我创建这样的文件:

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是package-info.java和元素所在的包。

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

定义了Foo对象,其元素如下:

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

@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?

推荐答案

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

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:

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....

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

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

这篇关于删除ns2作为默认名称空间前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆