philein-sophos
philein-sophos

Reputation: 372

Cypress parse XML response

I have an api, which return xml data.

I am writing a testcase in cypress, through which I am requesting that api, which returns following data

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Student>
    <Roll>55</Roll>
    <Name>ABC</Name>
</Student>

How do I parse this response body and get Name of the student from this response ?

Upvotes: 2

Views: 5131

Answers (2)

user14783414
user14783414

Reputation:

Synchronously, with jQuery

const xml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <Student>
    <Roll>55</Roll>
    <Name>ABC</Name>
  </Student>`

it('parses the student name from xml', () => {

  function xmlProperty(xml, property) {
    return Cypress.$(Cypress.$.parseXML(xml)).find(property).text()
  }

  const name = xmlProperty(xml, 'Name') 
  console.log(name)

})

or in a Cypress command chain

const xml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <Student>
    <Roll>55</Roll>
    <Name>ABC</Name>
  </Student>`

it('parses student name in a Cypress command', () => {

  cy.wrap(Cypress.$(xml))
    .then(xml => xml.filter('student').find('name').text())
    .should('eq', 'ABC')
})

Upvotes: 6

Rosen Mihaylov
Rosen Mihaylov

Reputation: 1427

Edi: I made a search and found a similar question that has good solutions that seems to be working

 const text = "<string>This is my xml</string>"; //API response in XML
const parser = new DOMParser();
const xmlDOM = parser.parseFromString(text,"text/xml");
const value = xmlDOM.getElementsByTagName("string")[0].childNodes[0].nodeValue;
console.log(value)

Upvotes: 0

Related Questions