Is it possible to bind xml prefix→namespace mapping to a map using javax.xml.bind.* annotations?
Something like:
class FooPOJO {
...
#Namespacebindingannotation
Map<String,String> prefixToNamespaceMap;
...
}
And in the xml
<foo
xmlns="http://foo.com"
xmlns:bar="http://bar.com"
xmlns:baz="http://baz.com">
...
When unmarshaling the xml, prefixToNamespaceMap will map the 3 prefixes to their appropriate namespaces.
You want to dynamically extract the namespaces URIs and the prefixes from the XML? That's a genuinely bad idea.
XML namespaces are part of the contract between your application code and the XML it processes. They ought to be hard-coded into your application.
The reason is simple. These XMLs look different but are all the same document:
<foo:root xmlns:foo="http://main/ns" xmlns:bar="http://secondary/ns">
<foo:child bar:attr="1234">some data</foo:child>
</foo:root>
or
<bar:root xmlns:bar="http://main/ns" xmlns:foo="http://secondary/ns">
<bar:child foo:attr="1234">some data</bar:child>
</bar:root>
or
<root xmlns="http://main/ns" xmlns:baz="http://secondary/ns">
<child baz:attr="1234">some data</child>
</root>
So if you extract namespaces dynamically from them, your subsequent code will inevitably (and unnecessarily) break.
Use actual namespace URIs in your code and choose prefixes to your liking - prefixes are ephemeral, they don't have to match up with the XML files. XML is strongly typed data, treat it accordingly.
In other words, namespace prefixes are aliases, a convenience facility, they only exist in serialized data. They exist in XML, they don't exist in the DOM. They exist in your application's XPath expressions, they don't exist in the abstract tree the XPath expressions are parsed into. Those are two completely separate domains. If the same prefixes are used in both domains, that's entirely coincidental. Don't build application logic that transfers prefixes from one domain to the other, as this is bound to break.
Related
I have the situation there is an web service implemented in old Visual Studio 2008, which accepts the SOAP requests with content having namespaces only in this form:
<Root xmlns="http://A">
<A>
<A1 />
</A>
<B xmlns="http://B">
<B1 />
</B>
</Root>
All other forms of the XML (unqualified, or qualified with namespace prefix) are causing problems even if the wsdl and referenced xsd structures are manipulated and modified in various ways and the service is recompiled in Visual Studio 2008, the author of the ASP.NET web service is not able to get any other form of XML working.
Is there any way how to achieve the generation of the classes for our Java client accessing this web service by using the external JAXB binding specification, used during the class generation, so the XML would be from the objects marshalled in the above described form?
Am I right, if I think, this could be achieved by the forcing the JAXB to generate the class(ses in multiple directories)
package-info.java
instead of the default form
#javax.xml.bind.annotation.XmlSchema(
namespace = "http://some/custom/namespace",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package some.custom.namespace;
in the following form?
#javax.xml.bind.annotation.XmlSchema(
namespace = "http://some/custom/namespace",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
xmlns = {#XmlNs(prefix = "", namespaceURI = "http://some/custom/namespace")})
package some.custom.namespace;
and if I am right, is there any way to do it? I am unfamiliar with writing the XJB bindings, so any pointer would be appreciated...
Or maybe, after the generation the source code of this class should be postprocessed by something like ant task, which would modify the initially generated JAXB form into the form I think it was the desired content of the class package-info.java?
Could this be somehow achieved by one universal jxb binding file for all usages without necessity to modify it for every namespace folder creating its own package?
I hope this could really work even with multiple different namespaces without prefixes, because the xmlns definitions are then used in JAXBContextImpl as a set of XmlNs types, so if there is an prefix or not hopefully should not matter... Am I right?
This is my first question on StackOverflow in general, so please bear with me.
I have an issue with marshalling XML that uses the default prefix for different namespaces. Each element that uses the default prefix should specify its namespace in its opening tag. An example what I'm trying to achieve would be something like this (simplified):
<parent xmlns="parentNamespace" xmlns:cd1="child1Namespace">
<cd1:child1/>
<child2 xmlns="child2Namespace">
...
</child2>
<child3 xmlns="child3Namespace">
...
</child3>
</parent>
I have tried setting namespaces prefixes in package-info.java of the object I'm trying to marshall using annotations like this:
#javax.xml.bind.annotation.XmlSchema(
namespace = "parentNamespace",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
xmlns = {
#XmlNs(prefix="",parentNamespace"),
#XmlNs(prefix="cd1", namespaceURI="child1Namespace"),
#XmlNs(prefix="", namespaceURI="child2Namespace"),
#XmlNs(prefix="", namespaceURI="child3Namespace")
}
)
But the end result is something like this:
<ns1:parent xmlns:ns1="parentNamespace" xmlns:cd1="child1Namespace" xmlns="child2Namespace xmlns:ns2="child3Namespace"<
<cd1:child1/>
<child2>
...
</child2>
<ns2:child3>
...
</ns2:child3>
</ns1:parent>
Which really is a valid XML, but unfortunately for reasons that are outside my control isn't good enough (doesn't pass validation). Also note that solution using Java 8 is highly preferable as I wouldn't want to mess with NamespacePrefixMapper if at all possible (if it even works).
So the question is: Is it possible to generate XML using JAXB that uses same prefix for multiple namespaces and how?
I have generated Java classes from an XSD, and in my XML responses I am getting a ns2: prefix which I do not need.
For example, I am getting this response:
<ns2:location xmlns:ns2="http://www.example.com/">
<ns2:response/>
</ns2:location>
But the response I am expecting is as follows:
<location>
<response/>
</location>
Your example shows not just a namespace prefix (ns2) declaration but also an actual namespace (http://www.example.com/ for the location and response elements) as not being desired.
If you have full control over the XSD, you can remove the
targetNamespace="http://www.example.com/"
attribute from the xs:schema element in the XSD. Elements of XML documents conforming to this XSD will then no longer be in any namespace, and your generated Java classes will reflect this new setting.
However, be aware that deleting (or changing) targetNamespace effectively changes the names of the components defined in the XSD. Think twice about making such a change if the XSD is defined by another party or otherwise already in use by others.
I have an XML content without defined attributes, like this:
<rootElement>
<subElement1/>
</rootElement>
I want to populate this XML content with required attributes defined in XML Schema (XSD) for this XML.
For example, according to XSD subElement1 has required attribute 'id'.
What is the best way (for Java processing) to detect that and add such attributes to XML?
We need to add required attributes and set appropriate values for them.
As a result for example above we need to have the following XML:
<rootElement>
<subElement1 id="some-value"/>
</rootElement>
In the XML schema definition, i.e. XSD file, attributes are optional by default. To make an attribute required, you have to define:
<xs:attribute name="surname" type="xs:string" use="required"/>
You will find a very good introduction on XML and XML Schema Definitions, i.e. XSD, on W3 Schools.
In Java the equivalent of defining a XML schema is using JAXB, i.e. Java API for XML Binding that is included into Java SE. There you would define, e.g.
#XmlRootElement
public class Person { public #XmlAttribute(required=true) String surname; }
Hope this could clarify your question.
I would suggest you to use JAXB for that. Search the Internet for tutorials.
Steps to proceed further with JAXB,
Generate Java files using JAXB by providing the schema
Unmarshal your XML to generated Java classes (beans). Don't do validation or set validation handler here.
Populate those classes with appropriate values. required elements can be found using annotation look up. JAXB annotation for element would look like something, #XmlElement(name = "ElementName", required = true). And an attribute annotation would be something similar to this, #XmlAttribute(required = true)
Marshal your bean back to XML. You can validate your bean using ValidationHandler, while marshalling. Below is the sample code snippet,
marshller = JAXBContext.newInstance(pkgOrClassName).createUnmarshaller();
marshller.setSchema(getSchema(xsd)); // skip this line for unmarshaller
marshller.setEventHandler(new ValidationHandler()); // skip this line for unmarshaller
Use a DOM parser.Has methods to traverse XML trees, access, insert, and delete nodes
I have had the same idea of Cris but I think that with this validator you don't have information about the point in which you have had the error.
I think that you have to create or extend your own validator.
I am creating amazon feed, the feed xml should be like:
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
I am using jaxb to generate xml files from java classes, I used NamespacePrefixMapperImpl from jaxb samples to add namespaces to the xml. But currently it generates the root like:
<AmazonEnvelope xmlns:xsi:noNamespaceSchemaLocation="amzn-envelope.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
how I can remove the xmlns from amzn-envelope.xsd??
Here's the mapping I used in NamespacePrefixMapperImpl
if( "http://www.w3.org/2001/XMLSchema-instance".equals(namespaceUri) )
return "xsi";
if("amzn-envelope.xsd".equals(namespaceUri))
return "xsi:noNamespaceSchemaLocation";
I found a property at Marshaller that can add the amzn-envelope.xsd:
marshaller.setProperty("jaxb.noNamespaceSchemaLocation", "amzn-envelope.xsd");
and left the NamespacePrefixMapper to add the "http://www.w3.org/2001/XMLSchema-instance".
Hope this helps others.
If I understand your intent, your document has a default namespace, and you're trying to add the schemalLocation for that namespace.
NamespacePrefixMapper won't let you do this, it's useful only for picking a prefix for a namespace. There are no namespaces in this document, and so no useful way of using NamespacePrefixMapper. It can't be used for adding schemaLocation hints - those are treated specially by JAXB, and you're just confusing it.
Are you sure you need the noNamespaceSchemaLocation="amzn-envelope.xsd" at all? Have you tried sending it to the web service without it?