gotnull
gotnull

Reputation: 27214

Get node value in XML using jQuery

I'm trying to parse the following XML:

<AssetImageModel xmlns="http://schemas.datacontract.org/2004/07/ErgonFileService.Model" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <AssetId>00000000-0000-0000-0000-000000000000</AssetId>
    <AssetImageId>b74af53a-91e6-83f5-26f9-e1719ad5fd05</AssetImageId>
    <ImagePath i:nil="true"/>
    <IsDeleted>false</IsDeleted>
    <Modified>false</Modified>
    <Version>0</Version>
</AssetImageModel>

In order to retrieve for example the AssetImageId value. What would be the easiest way to achieve this using either JS or jQuery?

Upvotes: 3

Views: 18088

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

If you are having a xml text then use $.parseXML() to parse it to a xml object then use find() to locate the element.

var text = '<AssetImageModel xmlns="http://schemas.datacontract.org/2004/07/ErgonFileService.Model" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><AssetId>00000000-0000-0000-0000-000000000000</AssetId><AssetImageId>b74af53a-91e6-83f5-26f9-e1719ad5fd05</AssetImageId><ImagePath i:nil="true"/><IsDeleted>false</IsDeleted><Modified>false</Modified><Version>0</Version></AssetImageModel>'

var xml = $.parseXML(text);
console.log($(xml).find('AssetImageId').text())

Demo: Fiddle

If you are using ajax then set the dataType: 'xml' so that you can get the parsed object as the data in your success handler

Demo: Fiddle

Upvotes: 10

Related Questions