Need help in converting XML to JS

179 views Asked by At

I'm using fast-xml-parser and it can parse some of the data we get from an API but not consistent. There is this specific response that cannot be parsed to JS object.

<?xml version="1.0" encoding="utf-8"?>
<DataSet xmlns="http://www.pepid.com/webservices/">
    <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
        <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
            <xs:complexType>
                <xs:choice minOccurs="0" maxOccurs="unbounded">
                    <xs:element name="ContentSearchIndex">
                        <xs:complexType>
                            <xs:sequence>
                                <xs:element name="Pos" type="xs:int" minOccurs="0" />
                                <xs:element name="Content_Id" type="xs:int" minOccurs="0" />
                                <xs:element name="Title" type="xs:string" minOccurs="0" />
                            </xs:sequence>
                        </xs:complexType>
                    </xs:element>
                </xs:choice>
            </xs:complexType>
        </xs:element>
    </xs:schema>
    <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
        <NewDataSet xmlns="">
            <ContentSearchIndex diffgr:id="ContentSearchIndex1" msdata:rowOrder="0">
                <Pos>8412</Pos>
                <Content_Id>401687</Content_Id>
                <Title>Headache</Title>
            </ContentSearchIndex>
        </NewDataSet>
    </diffgr:diffgram>
</DataSet>

The code that results to that is this below:

return fetch(url)
  .then((response) => response.text())
  .then(async (text) => {
    const obj = parse(text);
    if (obj) {
      console.log(obj);
      return obj;

I got this codes from https://www.pluralsight.com/guides/fetch-and-populate-xml-data-in-react-native and it can parse some of the responses but not the one mentioned above.

The only data that I need is this below in JS format but I want to do it properly using fast-xml-parser. I'm thinking I only need some options to make it parse that response properly without resorting to hacky approach of reading the entire response letter by letter.

<Pos>8412</Pos>
<Content_Id>401687</Content_Id>
<Title>Headache</Title>
1

There are 1 answers

1
Koli On

I don't think you can convert a XML File to JS directly but you can use it in a JS for really cool things.