问题
I am using camel to route messages to a Webservice. The Messages are like XML but without namespaces/prefixes. The problem now is that the Webservice expects the XML but with the appropriate namespaces for each element. So as an example:
<a>
<b>value_b</b>
<c>value_c</c>
</a>
is what im getting in, but what needs to be sent out should look like this
<a xmlns:n1="http://yadda-ns1.com" xmlns:n2="http://yadda-ns2.com">
<ns1:b>value_b</ns1:b>
<ns2:c>value_c</ns2:c>
</a>
if it was the same namespace on all elements i would have just used an xslt to add it. But its mostly 2 or 3 different namespaces.
Now is it possible to add the namespaces in my camel route? I had the idea to use jaxb to marshal from the "incomplete" XML to the "complete" one (with XML), would this work? I was trying this but did not succeed yet.
Or does someone have a different idea? What i also have in my project is the XSDs and JAXB Annotated Classes so these can also be used and the messages are identical apart from the missing namespace.
Best Regards
Thomas
回答1:
You could transform the XML with a stylesheet such as the one below to modify the elements to be bound to the appropriate namespaces:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
xmlns:ns1="http:yadayada-ns1.com"
xmlns:ns2="http:yadayada-ns2.com">
<xsl:output indent="yes"/>
<!-- identity template that copies content(unless more specific templates match) -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- Make the "a" elements in the ns1 namespace -->
<xsl:template match="a">
<xsl:element name="ns1:{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<!-- Make the "b" and "c" elements in the ns2 namespace -->
<xsl:template match="b|c">
<xsl:element name="ns2:{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
来源:https://stackoverflow.com/questions/35749350/add-namespace-and-prefix-to-xml