473,746 Members | 2,311 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to declare namespace prefix in Java?

I want to declare namespace prefix in the Envelope element (i.e.
xmlns:xsi and xmlns:xsd) so that the document will be serialized to
look like the following. However, I don't know the right way to do
that in Java.

<?xml version='1.0' encoding='UTF-8'?>
xmlns:SOAP-ENV='http://schemas.xmlsoap .org/soap/envelope/'
xmlns:xsi='http ://www.w3.org/1999/XMLSchema-instance'
xmlns:xsd='http ://www.w3.org/1999/XMLSchema'>
<ns1:doSpelling Suggestion
xmlns:ns1='urn: GoogleSearch'

SOAP-ENV:encodingSty le='http://schemas.xmlsoap .org/soap/encoding/'>
<key xsi:type='xsd:s tring'>mykey</key>
<phrase xsi:type='xsd:s tring'>word2che ck</phrase>
</ns1:doSpellingS uggestion>
Currently, my program is as follows:

Document doc =
impl.createDocu ment("http://schemas.xmlsoap .org/soap/envelope/",
Element root = doc.getDocument Element();
/* I doubt this is the right way to declare namespace prefix */
root.setAttribu te("xmlns:xsi" ,
root.setAttribu te("xmlns:xsd" , "http://www.w3.org/1999/XMLSchema");

Element body =
doc.createEleme ntNS("http://schemas.xmlsoap .org/soap/envelope/",
root.appendChil d(body);

Element doSpellingSugge stion = doc.createEleme ntNS("urn:Googl eSearch",
"ns1:doSpelling Suggestion");
doSpellingSugge stion.setAttrib uteNS("http://schemas.xmlsoap .org/soap/envelope/",
"SOAP-ENV:encodingSty le",
"http://schemas.xmlsoap .org/soap/encoding/");
body.appendChil d(doSpellingSug gestion);

Element key = doc.createEleme nt("key");
/ * well, i can use setAttribute() to get rid of the extra namespace in
the output, but is there a better way?*/
key.setAttribut eNS("http://www.w3.org/1999/XMLSchema-instance",
"xsi:type", "xsd:string ");
doSpellingSugge stion.appendChi ld(key)

And the output looks like
xmlns:SOAP-ENV="http://schemas.xmlsoap .org/soap/envelope/"
xmlns:xsd="http ://www.w3.org/1999/XMLSchema"
xmlns:xsi="http ://www.w3.org/1999/XMLSchema-instance"><SOAP-ENV:Body><ns1:d oSpellingSugges tion
xmlns:ns1="urn: GoogleSearch"
SOAP-ENV:encodingSty le="http://schemas.xmlsoap .org/soap/encoding/"><key
xmlns:xsi="http ://www.w3.org/1999/XMLSchema-instance"
xsi:type="xsd:s tring">mykey</key><phrase
xmlns:xsi="http ://www.w3.org/1999/XMLSchema-instance"
xsi:type="xsd:s tring">word2che ck</phrase></ns1:doSpellingS uggestion></SOAP-ENV:Body></SOAP-ENV:Envelope>

How do I get rid of the superfluous namespace thingy in the <key> and
<phrase> element? Thanks a lot!

Mar 14 '06 #1
2 18729
If you're working with the DOM, there are two answers to this.

One is that, in many cases, it isn't strictly necessary to have an
actual namespace declaration. Use the proper createElementNS and
createAttribute NS directives, and the code which serializes the DOM out
to XML syntax should be able to create delarations automatically. See
the DOM level 3 working draft for a description of the algorithms
typically used to do namespace reconcilliation in the DOM.

On the other hand, some programs want an explicit namespace declaration
in the DOM for internal purposes, and creating one at a higher level of
the document will avoid potentially having to generate one at multiple
places lower down. So the DOM permits you to do this; the trick is to
use createAttribute NS or setAttributeNS to create an attribute in the
"namespace for namespaces" with the prefix xmlns:, the localname set to
the prefix you want to define, and the value being the URI you want to
bind that prefix to. Thus, uour example should be coded as:

root.setAttribu teNS("http://www.w3.org/2000/xmlns/",
"xmlns:xsi" ,

Important Note: If you're working with namespaces, you ABSOLUTELY MUST
NOT use the setAttribute, createAttribute , or createElement calls.
****ONLY**** the setAttributeNS, createAttribute NS, and createElementNS
versions are compatable with namespace-aware processing. (There are good
but ugly reasons why we couldn't deprecate the older calls, but they
should be considered obsolete except for backward compatability with
code that is intended to work with a Level 1 DOM.)

See DOM Level 2's description of how to work with namespaces; a copy can
be found at
How do I get rid of the superfluous namespace thingy in the <key> and
<phrase> element? Thanks a lot!

If the above changes don't resolve this for you, it's possible the
serializer you're using is broken...

() ASCII Ribbon Campaign | Joe Kesselman
/\ Stamp out HTML e-mail! | System architexture and kinetic poetry
Mar 15 '06 #2
Thanks Joe. You rock!!!

Mar 15 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

by: Divick | last post by:
Hi all, does any one know what is the right way to forward declare classes within namespaces. Though I have been using the syntax as follows but it doesn't sound good to me. namespace myVeryOwnNamespace { class myClass1; }
by: Krishna Tulasi via .NET 247 | last post by:
Hi, I am having trouble with creation of XML programmatically using .NET. Specifically Im trying to create an element which looks like below and insert into an existing xml doc: <Worksheet ss:Name="TKCSheet1"> </Worksheet> The existing xml doc is: <?xml version="1.0"?> <?mso-application progid="Excel.Sheet"?>
by: pneumoconi | last post by:
I've read a lot of posts on this subject each with a slightly different issue and from what I gather my code is fine. But its not. I'm trying to pull out the SQL query from a SQL report document which looks something like this: <?xml version="1.0" encoding="utf-8"?> <Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2003/10/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">...
by: David Thielen | last post by:
Hi; I set up my xml as follows: XmlDocument xml = new XmlDocument(); xml.Load(File.Open("data.xml", FileMode.Open, FileAccess.Read)); XmlNamespaceManager context = new XmlNamespaceManager(xml.NameTable); context.AddNamespace("", "http://www.test.org"); context.AddNamespace("sns", "http://www.test.org/sub"); XmlNode node = xml.SelectSingleNode("/root", context);
by: izhar.wallach | last post by:
Hi all, I've noticed an odd behavior of the linker while trying to compile the code below. The linking did not fail even though variable a1 (A2.cpp) was defined as extern in namespace A2 while its actual deceleration was in namespace A1 (main.cpp). Thus, the assignment a1 = &a2 (A2.cpp) should have failed. I used the following for compilation: g++ -Wall -pedantic -ansi main.cpp A2.cpp gcc version:
by: VanOrton | last post by:
Hi all, When XercesDOMParser parses an XML document with a Schema instance, by default it adds all missing default and fixed attributes. I have the impression though that it misses the namespace prefices... I'm using Xerces 2.5.0. Here's a document parsed by Xerces:
by: jacksu | last post by:
I have a simple program to run xpath with xerces 1_2_7 XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); XPathExpression xp = xPath.compile(strXpr); System.out.println(xp.evaluate(new InputSource(new FileInputStream("a.xml"))));
by: scottpet | last post by:
Hi, I want to add a namespace prefix to the root node of an object I am serializing to XML. I have been reading though this article: http://msdn2.microsoft.com/en-gb/library/system.xml.serialization.xmlnamespacedeclarationsattribute.aspx I get namespace prefixes in the document, but not on the root node. Specifically, the serializer does not work as described in the last
by: Philipp | last post by:
Hello, I am not able to read the namespace for my elements correctly. Could somebody point me to my error. Thank you. Philipp Compilable example: import java.io.ByteArrayInputStream; import java.io.InputStream; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document;
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.