Generating XML file from XSD causes unwanted prefix on root node
I am using XML spy to automatically generate an XML file from an XSD. However, it always seems to prefix my root element with n1: or n2: e.g. it would generate something like to following
<?xml version="1.0"?>
<n2:EmployeeData>
<Employee>
<name>xyz</name>
<dateOfBirth>10.10.10</dateOfBirth>开发者_运维百科
<email>a@a.com</email>
</Employee>
</n2:EmployeeData>
I would like it to generate the following:
<?xml version="1.0"?>
<EmployeeData>
<Employee>
<name>xyz</name>
<dateOfBirth>10.10.10</dateOfBirth>
<email>a@a.com</email>
</Employee>
</EmployeeData>
That is similar to when in Java JAXB NamespacePrefixMapper is not set. If you declare namespace uri and prefix then XML will be generated with the right prefix (or no prefix) and namespace uri. Check in XML Spy has an option for setting namespace prefixes.
First of all: namespaces are a fundamental concept in XML. If you are not familiar with namespaces, please take time to learn and understand them. Even though namespaces are URIs, they do not need to (but can) point to any existing web page. They are just unique identifiers.
Because your XML Schema has a target namespace, the root element of an instance document must be in that namespace. You can use some other namespace prefix in your instance document if you want, just make sure that you also have a namespace definition that binds your prefix to that required target namespace URI. Like @skaffman commented, the XML you posted is actually not well-formed, because it uses a namespace prefix without a prefix-to-namespace mapping. Another way to deal with your issue is to remove the prefix and define a default namespace in the root element. If your instance document shouldn't be in any namespace, then your schema is incorrect and it should be fixed by removing the targetNamespace
attribute.
By the way, in your document only the root element belongs to a namespace. This is not a common practice and I guess that in this case such result was caused by an unintentional feature in your schema document. By default, only the elements that are declared globally in the schema document will be in the target namespace. This can be changed by setting elementFormDefault="qualified"
attribute on the <xs:schema>
element. This attribute makes sure that also elements that locally are declared in this schema do belong to the target namespace. The default value for that attribute is false, which is applied if the attribute is missing.
精彩评论