kostja
kostja

Reputation: 61538

How to determine all namespaces in an XML document

I am trying to use XPath queries on a document with multiple namespaces and need to define a NamespaceContext. The only way to retrieve all namespaces I can think of, would be to iterate over all nodes and attributes and collect their namespace URIs and prefixes explicitly. This seems very inefficient, and I have doubts that it is the best practice.

How should it be done?
Thank you

Upvotes: 1

Views: 662

Answers (1)

Riyad Kalla
Riyad Kalla

Reputation: 10702

Because namespaces can be defined in both the header of the XML doc as well as the elements themselves, you are correct; if you need EVERY namespace used in a doc you would need to process the entire doc (including all imports if you want to be 100% complete).

If you are wanting people to be able to query your doc like a database with XPath-esque queries, you'll likely want to load up the doc into an in-memory representation that can be queried quickly anyway.

Given that you have to process the whole thing into memory anyway, that would be your opportunity to parse all the namespaces.

NOTE: I am ignoring the "why" you would need all the namespaces, I just assume you need them, in which case your assumption of processing the whole doc is correct.

Upvotes: 2

Related Questions