Hagai Cibulski
Hagai Cibulski

Reputation: 4541

Java DOM parser to filter out SOAP namespace-prefixes?

I am parsing a SOAP that has elements with namespace-prefixed names:

<ns1:equipmentType>G</ns1:equipmentType>

So the parser faithfully creates elements with namespace-prefixed names:

ns1:equipmentType

Can I somehow tell the parser to filter out all the namespace-prefixes? so the element names will be like:

equipmentType

My code:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = documentBuilder.parse(inputStream);

Upvotes: 1

Views: 2193

Answers (2)

Coffee Monkey
Coffee Monkey

Reputation: 472

Make sure to do setNamespaceAware(true) on the DocumentBuilderFactory.

On the resulting Document instance you can then use getLocalName() to get element names without the prefix.

You can also use for example getElementsByTagNameNS() where you provide the namespace URI and the local tag name to find the elements you need. This decouples your code from the actual prefix that is being used for that namespace inside that particular document. I'm thinking this is actually what you're after.

Upvotes: 1

Holger
Holger

Reputation: 298539

I don’t see that you set the parser to be namespace-aware so that’s most probably the missing thing here.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(inputStream);

Then invoking getLocalName() on a node will give you the name without any prefix.

However if that’s not enough for you and you really want to get rid of the name-spaces at all you can use an XML transformation to create a new DOM tree without the name-spaces:

Transformer trans = TransformerFactory.newInstance().newTransformer(
  new StreamSource(new StringReader("<?xml version='1.0'?>"
   +"<stylesheet xmlns='http://www.w3.org/1999/XSL/Transform' version='1.0'>"
   +  "<template match='*' priority='1'>"
   +    "<element name='{local-name()}'><apply-templates select='@*|node()'/></element>"
   +  "</template>"
   +  "<template match='@*' priority='0'>"
   +    "<attribute name='{local-name()}'><value-of select='.'/></attribute>"
   +  "</template>"
   +  "<template match='node()' priority='-1'>"
   +    "<copy><apply-templates select='@*|node()'/></copy>"
   +  "</template>"
   +"</stylesheet>")));
DOMResult result=new DOMResult();
trans.transform(new DOMSource(document), result);
document=(Document)result.getNode();

Upvotes: 6

Related Questions