qs library Javascript/React read xml response attributes

103 Views Asked by At

I have a react piece of code like below,

const urlEncodePostData = qs.stringify(postData);
    post(url, urlEncodePostData).then(
      (response) => {
        const { data } = response;
        const xmlData = response.data;
        const rowData = loadRowData(xmlData, 'value');
        if (rowData[0].value != null) {
          formSubmitedMessage = rowData[0].value;
        }

I am posting to the server, and getting a response in the below format,

<XML>
<row ID="3123" PatientID="3454">
</row>
</xml>

How should I read the PatientID attribute from the response?

1

There are 1 best solutions below

0
ThW On BEST ANSWER

Be aware that XML is case sensitive. The closing tag has to match the opening tag.

<xml>
  <row ID="3123" PatientID="3454"></row>
</xml>

You can parse the returned XML with DOM and use QuerySelector (or Xpath for more complex XML).

const xmlDocument = (new DOMParser()).parseFromString(getXMLString(), 'text/xml');

const row = xmlDocument.querySelector('row');
const data = {
  'ID': row?.getAttribute('ID'),
  'PatientID': row?.getAttribute('PatientID')
};

console.log(data);

function getXMLString() {
  return `<?xml version="1.0" encoding="UTF-8"?><xml>
      <row ID="3123" PatientID="3454"></row>
    </xml>`;
}