whitebear
whitebear

Reputation: 12435

Parse xml and fetch by attributes

I have xml like this

<?xml version="1.0" encoding="UTF-8"?>
<resources>

<string name='Level0'>Beginner</string>
<string name='Level1'>Normal</string>
<string name='Level2'>Hard</string>
<string name='Level3'>Super Hard</string>

I want to pull out each item in <string> tag.

For now it is my code.

var xmlBody = xml.parse(contents);
var names = xmlBody.findAllElements('string');

total.map((node) => node.text).forEach(print); // testing, it returns text
total.map((node) => node.attributes).forEach(print);// testing, it returns attributes

 //Below is what I want to get. 

print(names.attribute('name','Level0').text)); // this is wrong...

It might be the basic knowledge of XML parser....

However I cant find the good documents.

Does anyone gives me the hint??

Upvotes: 0

Views: 1688

Answers (1)

Richard Heap
Richard Heap

Reputation: 51732

The following code should get you going:

  var document = parse(theXml);
  var allStringElements = document.findAllElements('string');

  // dissect the first element...
  var firstElement = allStringElements.first;
  print(firstElement.text);
  print(firstElement.attributes.first.value); // should really search the attributes for the one called 'name', but as there's only one...

  // or do something useful with the whole list
  for (var element in allStringElements) {
    print('${element.attributes.first.value}->${element.text}');
  }

The first two lines parse the document and extract the string tags as you are doing. This gives a list of elements (actually a lazy iterator...).

An element has text (from between the opening and closing tags) and attributes, which is another list - this time of all the attributes inside the opening tag.

As there's only one attribute, we can select it with first (though it would be better to use firstWhere and pass a predicate that selected by name=="name". The next two lines show printing those.

Finally we can loop over the whole list doing something with the key and value of the key-value pair. In this case just print them.

Upvotes: 3

Related Questions