-
Notifications
You must be signed in to change notification settings - Fork 5
Use Case: Getting a Single Element
Consider the following XML given as a string named xmlSource:
<?xml version="1.0"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<SendRequestRequest xmlns="urn://some-schema" xmlns:ns0="urn://another-schema">
<SenderProvidedRequestData Id="Ue7e71ce1-7ce3-4ca5-a689-1a8f2edbb1af">
<MessageID>3931cda8-3245-11ec-b0bc-000c293433a0</MessageID>
<ns0:MessagePrimaryContent>
<ExportDebtRequestsRequest>
<!-- ... and so on ... -->Find the first SenderProvidedRequestData element and get it as a js Object of the following structure:
{
Id: "Ue7e71ce1-7ce3-4ca5-a689-1a8f2edbb1af",
MessageID: "3931cda8-3245-11ec-b0bc-000c293433a0",
MessagePrimaryContent: {
ExportDebtRequestsRequest: {
// and so on
}
}
}const {XMLReader, XMLNode} = require ('xml-toolkit')
const data = await new XMLReader ({
filterElements : 'SenderProvidedRequestData',
map : XMLNode.toObject ({})
}).process (xmlSource).findFirst ()Here:
- an XMLReader is created;
- with the
filterElementsthat tells him to ignore anything before the firstSenderProvidedRequestDataelement occurs - and the
mapoption requiring the XMLNode.toObject transformation;
- with the
- the
processmethod implicitly creates an XMLLexer instance, performs all the necessary piping; - the
findFirstasynchronous method waits for the first result, then frees all the resources used and returns the result.
By default, yes (which is a standard practice with XML to JSON mapping).
But they are easy to reveal by using custom getName for XMLNode.toObject. For example:
map: XMLNode.toObject ({
getName: (localName, namespaceURI) => `{${namespaceURI}}${localName}`,
//...
},By supplying filterElements in the form of a function mapping XMLNode to Boolean:
filterElements: e =>
e.localName === 'SenderProvidedRequestData' &&
e.namespaceURI === 'urn://some-schema'Same as above: by specifying all necessary conditions as the filterElements function. See XMLNode page for more details on its properties.
The result will be null.
The result will be a string representing its text content. For instance, in the example above
const id = await new XMLReader ({
filterElements : 'MessageID',
map : XMLNode.toObject ({})
}).process (xmlSource).findFirst () // will be '3931cda8-3245-11ec-b0bc-000c293433a0'If the string is empty (zero length), null will be returned, as if the element is missing.