简体   繁体   中英

How to remove namespace prefix in Node.js

I am consuming a Web service in Node.js .

In the SOAP response, the elements come with a namespace prefix, like

<common_v26_0:BookingTravelerRef Key="lGZGs8IORfCNhaHEyHf0FA=="/>

How do remove these prefixes (such as common_v26_0: )?

You usually should not have to remove any prefixes. If your intention is to read data from the XML you can use namespace-aware methods from the DOM API or register a namespace if you are using XPath. In XPath you can also select data ignoring the namespace.

You have to discover what the namespace is. For example, in your SOAP response there should be an atrribute with a namespace declaration like xmlns:common_v26_0="your-namespace-uri" . You will need that your-namespace-uri to select data from your response:

var nsURI = "your-namespace-uri"; // replace with the actual namespace for `common_v26_0`

To select the BookingTravelerRef you use the DOM methods which have a NS suffix, for example:

var element = xmlnode.getElementsByTagNameNS(nsURI, 'BookingTravelerRef');
console.log(element.getAttribute("Key")); // unprefixed attributes belong in no namespace

If you are using XPath, you create a function which resolves namespaces. SOAP responses typically have many namespaces, so you can deal with all of them in the same function. But if you are only interested in one, you can also inline the function:

function resolver(prefix) {
    if (prefix='common_v26_0') { return "your-namespace-uri"; }
    // else if ... other namespaces you might want to resolve
    else return null;
}

Then you can use it in XPath expressions:

xmlnode.evaluate("//common_v26_0:BookingTravelerRef/@Key", xmlnode, resolver, XPathResult.ANY_TYPE, null);

Finally you can ignore namespaces in XPath matching all elements and then filtering by their local names:

xmlnode.evaluate("//*[local-name()='BookingTravelerRef']/@Key", ...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM