This is an XML example of what i'm trying to achieve:
<bookshelf>
<book id="1">
<title lang="en">Growing a Language</title>
<chapter number="1">What's a Language?</chapter>
<chapter number="2">Basics</chapter>
<chapter number="3">Examples</chapter>
<chapter number="4">Exam</chapter>
</book>
<book id="2">
<title lang="en">Learning XML</title>
<chapter number="1">What's XML?</chapter>
<chapter number="2">Theory</chapter>
</book>
<book id="3">
<title lang="en">Personal Computer</title>
<chapter number="1">What's a PC?</chapter>
<chapter number="2">Hardware</chapter>
<chapter number="3">Operating system</chapter>
</book>
</bookshelf>
Is there a way to get all the elements values given the book id number? something like:
document.getElement("bookshelf")?.getElement("book id=\"2\"")?.findAllElements("chapter").map((node) => node.firstChild).forEach(print);
CodePudding user response:
Use the xml
package, and parse the input to an XmlDocument
. Then navigate through it using findElements
to find the right child elements.
These return iterators, so you can use standard methods like first
and where
.
So, for example:
final doc = XmlDocument.parse(input);
doc
.findElements('bookshelf')
.first
.findElements('book')
.where((e) => e.getAttribute('id') == '2')
.forEach(print);
Depending on the structure of your XML, you may be able to skip finding the bookshelf and first
by using findAllElements('book')
CodePudding user response:
you can use xml2json package for converting json. enter link description here
In this link, i made an example.