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

Grammin picture Grammin · Jan 11, 2011 · Viewed 56.1k times · Source

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

Answer

Habeeb picture Habeeb · Jul 7, 2011

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 */
}