Skip to content

AddNamespace

Adds a namespace to the XML node with the given prefix and URI.

1
myXml.AddNamespace(prefix: string, ns: string):void

Parameters

string prefix
    The prefix to associate with the namespace.

string ns
    Namespace URI to associate with the prefix.

Remarks

XPath expressions cannot select namespaced elements without a prefix. Register a prefix for the namespace, then use it in every step of the XPath. The prefix only has to match the namespace URI, not the prefix used in the document.

In the following example, a SOAP service returns elements in the http://tempuri.org/ namespace:

Examples

SOAP response

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<GetResponse xmlns="http://tempuri.org/">
  <GetResult>
    <Item>
      <Id>9901</Id>
      <Name>Maintenance Service</Name>
      <VAT>18</VAT>
      <FirmNr>67</FirmNr>
    </Item>
    <Item>
      <Id>9902</Id>
      <Name>Cleaning Service</Name>
      <VAT>8</VAT>
      <FirmNr>68</FirmNr>
    </Item>
  </GetResult>
</GetResponse>

Register a prefix and query namespaced elements

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// the result of a SOAP call, for example $Services.ServiceCards.ServiceCardsSoap.Get({ ... })
var response = $Xml.Parse(
    '<GetResponse xmlns="http://tempuri.org/"><GetResult>' +
    '<Item><Id>9901</Id><Name>Maintenance Service</Name></Item>' +
    '<Item><Id>9902</Id><Name>Cleaning Service</Name></Item>' +
    '</GetResult></GetResponse>');

response.AddNamespace('tmp', 'http://tempuri.org/');

var names = response.SelectAll('tmp:GetResult/tmp:Item', function (item) {
    return item.Evaluate('tmp:Name');
});
// names: ['Maintenance Service', 'Cleaning Service']