Parsing XML file with XMLDoc lib - JpEncausse/SARAH-Documentation GitHub Wiki
The official documentation has been moved to http://wiki.sarah.encausse.net/
.
.
.
.
.
.
.
.
The object of this article is to present you a method to browse a XML file in Javascript. I chose to use this lib rather than xml2js because I find it simpler and more accessible approachable. But it’s a personal, and I have never succeeded to run xml2js in my pluging. This tutoriel aims to be very brief and explains the use of the lib within the plugin Zibase.
Just read the doc :p (and download the lib of course). https://npmjs.org/package/xmldoc https://github.com/nfarina/xmldoc
Let’s use a very simple XML file : children.xml
<?xml version="1.0" encoding="UTF-8"?>
<CHILDREN>
<CHILD name="luc" age="11" sex="M"/>
<CHILD name="sophie" age="12" sex="F"/>
<CHILD name="marie" age="13" sex="F"/>
<CHILD name="damien" age="14" sex="M"/>
<CHILD name="mathieu" age="15" sex="M"/>
</CHILDREN>
var xmldoc = require('./lib/xmldoc');
var fs = require('fs');
var xmlFile = fs.readFileSync(__dirname+'\\children.xml');
var file = new xmldoc.XmlDocument(xmlFile);
var myName = ‘marie’
var child = file.childWithAttribute(‘name, myName);
It will return us the entire line CHILD with the attribute name = 'myName ' (thus the third line, name=marie). Note that if several lines are concerned, it will return only the first one.
So, you can freely manipulate the line (and know the value of an attribute for example).
To reach an attribute, we use the syntax: [line].attr.[attribute] (by replacing decently line and attribute. For example:
if (child.attr.sex == 'M') { ... }
else { ... }
In this example, we shall enter into the else case because marie is a girl !!!
Well, it is finished. In this very small article, we saw how reaching a line of a xml with the value of one of its attributes thanks to the childWithAttribute method (), and we saw that it was easy, once the line found, to reach all the values of its attributes thanks to the [line].attr.[attribute] syntax. Do not hesitate to consult the Javascript code of the Zibase plugin to see a more elaborate and good case of use on, read the official documentation of XmlDoc to see the other available methods.