Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove namespaces from xml, using java dom?

I have the following code

DocumentBuilderFactory dbFactory_ = DocumentBuilderFactory.newInstance();
Document doc_;
DocumentBuilder dBuilder = dbFactory_.newDocumentBuilder();
StringReader reader = new StringReader(s);
InputSource inputSource = new InputSource(reader);
doc_ = dBuilder.parse(inputSource);
doc_.getDocumentElement().normalize();

Then I can do

doc_.getDocumentElement();

and get my first element but the problem is instead of being job the element is tns:job.

I know about and have tried to use:

dbFactory_.setNamespaceAware(true);

but that is just not what I'm looking for, I need something to completely get rid of namespaces.

Any help would be appreciated, Thanks,

Josh

like image 415
Grammin Avatar asked Jan 11 '11 18:01

Grammin


People also ask

How do I get rid of namespaces?

Remove namespaces using the Namespace Editor Determine the namespace for a node by selecting any object/node that uses the namespace. In the Namespace Editor, select the namespace you want to remove. Click Delete.

How do I change the default namespace in XML?

You can change the default namespace within a particular element by adding an xmlns attribute to the element. Example 4-4 is an XML document that initially sets the default namespace to http://www.w3.org/1999/xhtml for all the XHTML elements. This namespace declaration applies within most of the document.

How do I remove namespace prefix?

Once a namespace prefix is created, it cannot be changed or deleted. The workaround is to move all your code to a new Developer Organization, where you can setup the desired Namespace Prefix.


2 Answers

Use the Regex function. This will solve this issue:

public static String removeXmlStringNamespaceAndPreamble(String xmlString) {
  return xmlString.replaceAll("(<\\?[^<]*\\?>)?", ""). /* remove preamble */
  replaceAll("xmlns.*?(\"|\').*?(\"|\')", "") /* remove xmlns declaration */
  .replaceAll("(<)(\\w+:)(.*?>)", "$1$3") /* remove opening tag prefix */
  .replaceAll("(</)(\\w+:)(.*?>)", "$1$3"); /* remove closing tags prefix */
}
like image 170
Habeeb Avatar answered Oct 03 '22 18:10

Habeeb


For Element and Attribute nodes:

Node node = ...;
String name = node.getLocalName();

will give you the local part of the node's name.

See Node.getLocalName()

like image 38
robert_x44 Avatar answered Oct 03 '22 18:10

robert_x44