EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials XML Tutorial XML Array
Secondary Sidebar
XML Tutorial
  • Basic
    • What is XML?
    • XML Tags
    • XML URL
    • XPath Sibling
    • XML root element
    • XML Encryption
    • XML Parsing php
    • xml parsing with java
    • Dataset XML
    • XML Parser in C#
    • XML Tree
    • XML boolean
    • XML sitemap
    • XML Array
    • XML reserved characters
    • XML Viewer
    • XML Uses
    • XML Special Characters
    • XML generator
    • XML file format
    • XML DOM
    • XML ampersand
    • XML Mapping
    • XML File
    • XML Element
    • XML HttpRequest
    • XML XSD
    • XML Schema
    • XML Namespaces
    • XML Comments
    • XML Attributes
    • XML Encoding
    • XML Validation
    • XML CDATA
    • XML Database
    • XML Technologies
    • XML Error
    • XML DTD
    • XML Date
    • XML Parsers
    • String in XML
    • XML with CSS
    • XML Versions
    • XML Features
    • XML Commands
    • Servlet web.xml
    • XPath Injection
    • XPath Functions
    • XPath starts-with
    • XPath Selector
    • XPath Count
    • XPath XML
    • XML Parsing in Oracle
    • XML parsing in python
  • Xpath
    • What is XPath?
    • XPath namespace
    • XPath for JSON
    • XPath Last Element
    • Xpath Substring
    • XPath First Element
    • XPath local-name
    • XPath Multiple Attributes
    • XPath Matches
    • XPath Position
    • XPath Index
    • XPath regex
    • XPath id contains
    • XPath innertext
    • XPath Multiple Conditions
    • XPath Helper
    • XPath Generator
    • XPath ID
    • XPath Locator
  • Xquery
    • What is Xquery

XML Array

XML Array

Introduction to XML Array

XML Array has defined as a variable array grouping together the same items in the list and contains one or more child items. Arrays being a sequence of elements declared with the same name. A multi-dimensional Array is created for a collection of elements. The arrays are done by creating functions by pairs. Many elements are collected in each pair. DOM creates an XML element array with the parameters attribNamesArray and Values Array.

Syntax

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The General Syntax is shown as:

<?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 it. In the above Syntax, the array element has a name element and enclosed with the item tags. In this way, we can implement array types in any programming language.

How array work in XML?

Array works well in XML with C# Serialize that adds an attribute to an array element. In other words, we can say, adding objects after serialization. In this article, we have explained 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:

  1. file_get_contents (): This reads a file as string type helps to read the content of an XML file.
  2. simplexml_load_string ():  parsing an XML file to take relevant information as we have more APIs in the websites.
  3. json_ encode: It returns JSON values after encoding.
  4. 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, lastly, applying Serialization to an object.

Examples

The following Sections talks much about XML array and Attributes implemented in Serializable and PHP language.

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 different countries in the Android Application.

Output:

XML Array output 1

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, and 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:

XML Array output 2

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:

output 3

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 like this:

Output:

output 4

Conclusion

This article discussed how to use an array in an XML file using simple programming examples. This is useful when it comes to parsing and doing any manipulation on XML Documents. Coming to String array, they are more powerful, and the android application makes use of it to store string data in resource files.

Recommended Articles

This is a guide to XML Array. Here we discuss how to use an array in an XML file using simple programming examples and outputs. You may also look at the following articles to learn more –

  1. XML XSD
  2. XML Comments
  3. XML Database
  4. XML DTD
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more