Detect Default namespace (Unkown)

A

AGP

I am trying to parse out an XMl file and have it all working except there
are occasions whe the default namesapce will change and i need to account
for it. The namespace can be

xmlns="http://data.usgs.gov/mag/1.0"

or

xmlns="http://data.usgs.gov/mag/2.0"

or

xmlns="http://data.usgs.gov/dec/2.8"

These are examples and there could be many more.The data is more or less in
the same format as far as nodes and node names but how do I account for the
various namespaces. I will not know these ahead of time so was hoping there
was a way to parse these out of the header.

tia

AGP
 
M

Martin Honnen

AGP said:
I am trying to parse out an XMl file and have it all working except there
are occasions whe the default namesapce will change and i need to account
for it. The namespace can be

xmlns="http://data.usgs.gov/mag/1.0"

or

xmlns="http://data.usgs.gov/mag/2.0"

or

xmlns="http://data.usgs.gov/dec/2.8"

These are examples and there could be many more.The data is more or less in
the same format as far as nodes and node names but how do I account for the
various namespaces. I will not know these ahead of time so was hoping there
was a way to parse these out of the header.

Do you use LINQ to XML to deal with the XML? If so then you can simply do
Dim doc As XDocument = XDocument.Load("file.xml")
Dim ns As XNamespace = doc.Root.Name.Namespace
to get an XNamespace object, assuming the default namespace is defined
on the root element of your XML documents.
Then you can use that XNamespace object ns when trying to select
elements e.g.
Dim query = _
From foo In doc.Descendants(ns + "foo") _
...
The nice thing is that the approach even works if the root element has
no namespace declaration so you don't have to change the code if you
need to deal with different documents where some have a namespace and
some do not have one.
 
A

AGP

thanks. i think this will work. Incidentally if there are more than one
namespaeces how do I parse those out? I dont think Ill need them but i think
its good info to know.

AGP


Abel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top