Updated June 28, 2023
Introduction to XML Array
XML Array is defined as a variable array grouping the same items in the list and containing one or more child items. Arrays are a sequence of elements declared with the same name. A multidimensional Array is created for a collection of elements. The arrays are done by creating functions in pairs. Many elements are collected in each pair. DOM creates an XML element array with the parameters attribNamesArray and Values Array.
Syntax
The General Syntax is shown as follows:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array
name="integer_array_name">
<item>resource</item>
</array>
</resources>
Arrays are specified using Array elements that have data values on them. In the above Syntax, the array element has a name element and is enclosed with the item tags. In this way, we can implement array types in any programming language.
How does an array work in XML?
Array works well in XML with C# Serialize which adds an attribute to an array element. In other words, we can say adding objects after serialization. This article explains using C# and PHP programming concepts to take up XML Array. Let’s say an Array with a Specification like:
cds: An XML may look like this
type:array <cds> ‘mp2’ </cds>
lists: <cds> ‘mp3’ </cds>
type:string <cds> ‘mp4’ </cds>
Example:
- ‘mp2’
- mp3’
- mp4’
Let’s take a small sample code to understand the concept. First is our XML file Generation:
<Courses count= “3”>
<Java>little rat</ Java >
<XML>old rat</ XML >
</Courses>
The Corresponding C# code is
[XmlType(“Courses”)]
public class Courses
{
[XmlAttribute(“count”)]
public int Count {get; set; }
[XmlElement(“Courses”)] // now the array element will be as same as the object element Rats.
public string[]Courses { get; set;}
Next, in PHP, to convert XML file document into array structure: To do so, we need some functions to perform the task which is listed below:
- file_get_contents (): This reads a file as a string type and helps to read the content of an XML file.
- simplexml_load_string (): parsing an XML file to take relevant information as we have more web APIs.
- json_ encode: It returns JSON values after encoding.
- json_decode: It returns the decoded value.
Using multiple files in a single Array
<?PHP
foreach ($fil as $file) {
$xmlf= simplexml_load_file($file);
XMLToArrayFlat($xmlf, $xmlarray, $fil.':', true);
}
?>
Finally, in all the below examples, we have applied a property declared as arrays. Sometimes, a collection modifies the outer elements and applies Serialization to an object.
Examples
The following Sections talk much about XML arrays and Attributes implemented in Serializable and PHP languages.
Example #1
android.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="Welcome">Welcome! To my home page</string>
<string name="Web_name">General View</string>
<string-array name="EuropeCountry_array">
<List>Berlin</List>
<List>Vienna</List>
<List>Stockholm</List>
<List>Richard Nixon</List>
<List>Prague</List>
<List>Rome</List>
<List>Budapest</List>
<List>Amsterdam</List>
<List>London</List>
<List>Norway</List>
<List>Denmark</List>
</string-array>
</resources>
Explanation
Here is a simple example with an array list of countries in the Android Application.
Output:
Example #2 – Array Using PHP
new.php
<?php
libxml_use_internal_errors(TRUE);
$objDoc = simplexml_load_file("lib.xml");
if ($objDoc === FALSE) {
echo "Gives an error in the XML file.\n";
foreach(libxml_get_errors() as $error) {
echo $error->message;
}
exit;
}
$objJsonDoc = json_encode($objDoc);
$arrOutput = json_decode($objJsonDoc, TRUE);
echo "<pre>";
print_r($arrOutput);
?>
lib.xml
?xml version='1.0'?>
<Library>
<Department id="1">
<Bookname>XML Introduction</Bookname>
<author>O'reilla</author>
<address>
<Door>4201 Greenland Avenue</Door>
<city>New York</city>
<Country>United States</Country>
</address>
</Department>
<Department id="2">
<Bookname>Data Warehouse</Bookname>
<author>Mac meihelline</author>
<address>
<Door>5840 texas House</Door>
<city>Dallas</city>
<Country> Canada</Country>
</address>
</Department>
</Library>
Explanation
In the above code, we have used a function lib to enable users to handle errors. This allows us to catch XML errors. Next is the XML load file, which loads an XML file; the respective path is given in that. If it is parsed successfully, it returns True, if-else False. Following this line, the next statement, JSON, converts the XML object into JSON format. Therefore, the final output would be like this.
Output:
Example #3 – Converting Multidimensional Array into XML file
$array = array (
'School' => 'Bostin Secondary School',
'Student' => array (
'0' => array (
'Stdname' => 'Antony Sukesh',
'age' => '18'
),
'1' => array (
'Stdname' => 'Mahesh Das',
'age' => '20'
),
'2' => array (
'Stdname' => 'Subhashree vasin',
'age' => '19'
),
'3' => array (
'Stdname' => 'Vamssi Narayanan',
'age' => '21'
)
)
);
Function generation in a class PHP
function doXML($info) {
$head = $info['School'];
$rcount = count($info['Student']);
$xdc = new DOMDocument();
$root = $xdc -> appendChild($xdc ->
createElement("EDUCBA"));
$root -> appendChild($xdc ->
createElement("Welcome", $Welcome));
$root -> appendChild($xdc ->
createElement("No.of Std", $rcount));
$tabU = $root -> appendChild($xdc ->
createElement('count educba'));
foreach($info['Student'] as $uu) {
if (!empty($uu)) {
$tabU = $tabU -> appendChild($xdc ->
createElement('Student'));
foreach($uu as $kk => $val) {
$tabU -> appendChild($xdc ->
createElement($kk, $val));
}
}
}
$xdc -> formatOutput = true;
$fi_name = str_replace(' ', '_', $welcome) . '.xml';
$xdc -> save($fi_name);
return $fi_name;
}
Explanation
Here we are setting the root element bypassing the argument, and by default, all the key names of the array are named with an underscore. After executing this piece of code, the result would look like this:
Output:
Example #4
mol.xml
<?xml version="1.0"?>
<Chemical>
<molSubstance>
<mname>Hydrogen</mname>
<msymbol>H</msymbol>
<Mno> 1 </Mno>
<type>hydrophobic</type>
</molSubstance>
<molSubstance>
<mname>Lithium</mname>
<msymbol>li</msymbol>
<Mno>3</Mno>
<type>Sub-atomic</type>
</molSubstance>
</Chemical>
PHP file parsing an array
<?php
class LacticAcid {
var $mname;
var $msymbol;
var $Mno;
var $type;
function LacticAcid ($la)
{
foreach ($la as $l=>$vi)
$this->$l = $la[$l];
}
}
function readDb($filename)
{
$dt = implode("", file($filename));
$par = xml_parser_create();
xml_parser_set_option($par, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($par, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($par, $dt, $val, $tags);
xml_parser_free($par);
foreach ($tags as $kk=>$val) {
if ($kk == "molecule") {
$molrang = $val;
for ($k=0; $k < count($molrang); $k+=2) {
$offset = $molrang[$k] + 1;
$leng = $molrang[$k + 1] - $offset;
$tdb[] = parseMol(array_slice($val, $offset, $leng));
}
} else {
continue;
}
}
return $tdb;
}
function parse($mval)
{
for ($k=0; $k < count($mval); $k++) {
$mol[$mval[$k]["tag"]] = $mval[$k]["value"];
}
return new LacticAcid($mol);
}
$dba = readDatabase("mol.xml");
echo "** Database of LacticAcid objects:\n";
print_r($dba);
?>
Explanation
The output of the above code script shows this:
Output:
Conclusion
This article discussed using simple programming examples to use an array in an XML file. This is useful when it comes to parsing and doing any manipulation on XML Documents. Coming to a String array, they are more powerful, and the Android application uses it to store string data in resource files.
Recommended Articles
This is a guide to XML Array. Here we discuss using an array in an XML file using simple programming examples and outputs. You may also look at the following articles to learn more –