How to parse an XML structure using javascript jQuery

This is the XML file:

<Test> <Category> <SubCat> <Name>Name</Name> <Properties> <Key>Key</Key> <Value>Value</Value> </Properties> </SubCat> <SubCat> <Name>Name</Name> <SubCat> <Name>AnotherName</Name> <Properties> <Key>Key</Key> <Value>Value</Value> </Properties> </SubCat> </SubCat> </Category> </Test> 

I want to get a name. But only the name of the first SubCat. And the value of the property key. The problem is that SubCat exists twice.

I tried this:

 $(xml).find('SubCat').each(function() { var name = $(this).find("Name").text(); alert(name); } 

but it shows the name of the first and second SubCat.

I was looking for something like this.

 rootElement(Category).selectallchildren(SubCat).Name for the first SubCat Name rootElement(Category).selectallchildren(SubCat).(SubCat).Name for the second SubCat Name 

And the same explicit choice for key and values

+4
source share
1 answer

The trick here is to use jQuery to evaluate CSS3 selectors.

SubCat:nth-of-type(1) selects every first occurrence of SubCat with arbitrary parent elements.

So this should work:

 $(xml).find("SubCat:nth-of-type(1)").each(function(){ var name = $(this).find("Name").text(), property = { }; //use an object to store the key value tuple property[$(this).find("Properties Key").text()] = $(this).find("Properties Value").text(); console.log(name, property); }); //Output: //Name Object { Key="Value" } //AnotherName Object { Key="Value"} 

I hope you want; when writing my first answer, I obviously misinterpreted your question, sorry for the confusion ...

+1
source

Source: https://habr.com/ru/post/1440470/


All Articles