Skip to main content
Andreas Jansson
Inspiring
August 18, 2011
Answered

Namespace in XML

  • August 18, 2011
  • 1 reply
  • 1807 views

Hi,

How should you deal with namespaces in XML? As soon as there is a namespace (and there is in the string I currently get...), I can't manage to read any data out from the XML object I put the string inside.

Here is a samle piece of code I've been trying around with:

var myString = '<ArrayOfInt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/MyTest/MyTest"><int>0</int>  <int>0</int>  <int>0</int></ArrayOfInt>'
var myStringNoNS = '<ArrayOfInt>  <int>0</int>  <int>0</int>  <int>0</int></ArrayOfInt>'

var myXML = XML(myString);
var myXMLNoNs = XML(myStringNoNS);

$.writeln(myXML.children().length());
// 0

$.writeln(myXMLNoNs.children().length());
// 3

// Trying to remove the namespace part using the built-in method for it:
var myXML2 = myXML.removeNamespace(myXML.namespace());
$.writeln(myXML.namespace() == myXML2.namespace() );
// True... So the Namespace was not removed.

// Writing out namespace(): http://tempuri.org/MyTest/MyTest

My question is:

Primarily: how do I read the contents of the nodes as they exist in myXML

Or if that is not possible: How do I get rid of the namespace using a built-in function such as removeNamespace.

Of cource I could make some string replacements in the original xml string, or alter the incoming data... but that's not my question. That's more of a last way out.

Thanks,

Andreas

This topic has been closed for replies.
Correct answer absqua

See https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Processing_XML_with_E4X#Handling_namespaces

It looks like adding

default xml namespace "http://tempuri.org/MyTest/MyTest"

before your myXML declaration will allow you to access its non-namespaced (or default namespaced) children.

I can't say I understand the syntax, but it works.

Jeff

1 reply

absquaCorrect answer
Inspiring
August 18, 2011

See https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Processing_XML_with_E4X#Handling_namespaces

It looks like adding

default xml namespace "http://tempuri.org/MyTest/MyTest"

before your myXML declaration will allow you to access its non-namespaced (or default namespaced) children.

I can't say I understand the syntax, but it works.

Jeff

Andreas Jansson
Inspiring
August 22, 2011

Great!

(There's just a missing "=" in your example)

default xml namespace = "http://tempuri.org/MyTest/MyTest"

Thank you!