-1

I am trying to get values from an XML string which is like this

<ROOT>
<ADDALTERNATE>
<DATA>
<SELECTEDDATA ID="3534" NAME="sampleName" CODE="SampleCode" CODEIDS="133277,133278,133279,133280"/>
</DATA>
</ADDALTERNATE>
</ROOT>

How do I get the values from CODE tag from the given XML in javascript simplest way? tried different way it did not work .

  • https://developer.mozilla.org/en-US/docs/Web/Guide/Parsing_and_serializing_XML – phuzi Feb 25 '22 at 12:28
  • Use `new `[`DOMParser`](//developer.mozilla.org/docs/Web/API/DOMParser)`().parseFromString(` _your string here_ `, "text/xml").`[`querySelector`](//developer.mozilla.org/docs/Web/API/Document/querySelector)`("SELECTEDDATA");` to get an [`Element`](//developer.mozilla.org/docs/Web/API/Element). – Sebastian Simon Feb 25 '22 at 12:31

1 Answers1

0

You can use the DOMParser combined with a little XPATH to locate the required value.

const xmlStr = `<ROOT>
<ADDALTERNATE>
<DATA>
<SELECTEDDATA ID="3534" NAME="sampleName" CODE="SampleCode" CODEIDS="133277,133278,133279,133280"/>
</DATA>
</ADDALTERNATE>
</ROOT>`;

const parser = new DOMParser();
const doc = parser.parseFromString(xmlStr, "application/xml");

const code = doc.evaluate(`//SELECTEDDATA/@CODE`, doc, null, XPathResult.STRING_TYPE, null);
console.log(code.stringValue);
phuzi
  • 12,078
  • 3
  • 26
  • 50