jaxb anyelement namespace any instead of other

Viewed 386

I have a java jaxb annotated class

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement()
public class xmlDoc<T> {
@XmlMixed
@XmlAnyElement(lax=false)
   protected T content;
   public T getContent() {
      return this.content;
   }
   public void setContent(T t) {
        this.content = t;
   }
}

When I generate the xml schema using jaxb, I get the following output

<xs:complexType mixed="true" name="xmlDoc">
    <xs:sequence>
      <xs:any namespace="##other" processContents="skip"/>
    </xs:sequence>
  </xs:complexType>

Is there any annotation parameter in jaxb using which I can control the namespace of the any element type. I need ##any instead of ##other. Is this possible?

2 Answers

As mentioned in my comment above, I had a look at the source of the reference implementation and found out that the XmlSchemaGenerator simply writes ##other hard coded for the any element.

So, I'm replacing now the ##other with ##any after the file generation with the following method:

  private static void fixNamespaceOfAnyElementsFor(final File xsdFile) throws IOException, FileNotFoundException {
    final File tempFile = File.createTempFile("your_prefix", ".tmp");
    Files.move(xsdFile.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    try (final BufferedWriter writer = Files.newBufferedWriter(xsdFile.toPath())) {
      try (final Stream<String> lines = Files.lines(tempFile.toPath())) {
        lines.map(line -> line.replace("namespace=\"##other\"", "namespace=\"##any\""))
            .forEach(line -> {
              try {
                writer.write(line);
                writer.newLine();
              } catch (final IOException e) {
                throw new UncheckedIOException(e);
              }
            });
      }
    }
    Files.delete(tempFile.toPath());
  }

It basically moves the file to a temporary folder so that I can rewrite it on the original location replacing the attribute value. When finished the temp file is deleted.

NOTE: First I explored solutions with DOM and Stax but they all messed up the original formatting (pretty print) of the generator. Since I'm committing the generated XSD to git and need a consistent format on each generation, I decided to go for the simple line by line solution.

Related