代码之家  ›  专栏  ›  技术社区  ›  Iker Jimenez

jaxb,xs:any和targetnamespace

  •  1
  • Iker Jimenez  · 技术社区  · 14 年前

    我有一个定义以下模式的XSD:

    <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema"
           xmlns="http://example.com/2010/aa/"
           xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
           xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
           xmlns:aa="http://example.com/2010/aa/"
           targetNamespace="http://example.com/2010/aa/"
           elementFormDefault="qualified">
    ...
    <xs:element name="user" type="aa:User"/>
    <xs:complexType name="User">
      <xs:sequence>
          <xs:element ref="aa:firstName" minOccurs="0" maxOccurs="1"/>
          <xs:element ref="aa:lastName" minOccurs="0" maxOccurs="1"/>
          ...
          <xs:any namespace="##targetNamespace" processContents="skip" maxOccurs="unbounded" />
      </xs:sequence>
      <xs:anyAttribute processContents="skip" />
    </xs:complexType>
    
    <xs:element name="profile" type="aa:Profile"/>
    <xs:complexType name="Profile">
     <xs:sequence>
        <xs:element ref="aa:username" minOccurs="0" maxOccurs="1"/>
        <xs:element ref="aa:accountStatus" minOccurs="0" maxOccurs="1" />
        <xs:element ref="aa:roleid" minOccurs="0" maxOccurs="1"/>
        ...
        <xs:element ref="aa:userid"/>
     </xs:sequence>
     <xs:anyAttribute processContents="skip" />
    </xs:complexType>
    

    当JAXB对生成的对象进行编组时,它定义了以下内容:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <user xmlns:ns2="http://example.com/2010/aa/">...</user>
    
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <profile xmlns="http://example.com/2010/aa/">...</profile>
    

    看看一个名称空间是怎样的 xmlns:ns2 另一个是 XMLNS . 这是因为用户的所有元素都限定为aa名称空间,但由 任何一个 标记,因此需要定义两个名称空间。

    配置文件没有xs:any标记,不需要定义多个命名空间。这是我的解释,因为如果我从用户定义中删除xs:any,它将删除 NS2 从生成的XML。

    我怎么能告诉JAXB 目标命名空间 AA 是相同的命名空间,所以它不包括这两者吗?

    2 回复  |  直到 14 年前
        1
  •  3
  •   Community T.Woody    7 年前

    你可以尝试使用 NamespacePrefixMapper 要覆盖如何首先生成前缀:

    NamespacePrefixMapper mapper = new NamespacePrefixMapper() {
        public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
            return "";
        }
    };
    marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", mapper);
    

    我回来了 "" 所以只有一个默认前缀;根据需要实现一个更复杂的版本。

    这确实创建了对Sun类的依赖,这是JAXB引起的问题。请审阅 this other post . 底部的答案显示了如何修改 package-info.java 达到同样的效果。

        2
  •  1
  •   Community T.Woody    7 年前

    或者,不要使用专有的 Metro JAXB 分机,你可以用 MOXy JAXB . Moxy将使用@xmlschema package level注释中定义的命名空间前缀。

    有关详细信息,请参阅: