0% found this document useful (0 votes)
44 views38 pages

OOP2 (Part 7) - Structured Data

Here is the JSON data for the example profile view: { "id": 8839, "name": "Université Antonine", "following": true, "tweets": 1531, "statuses": [ { "created_at": "2015-03-21T17:32:00", "id": 579334, "text": "Bon travail pour vos examens!", "retweet_count": 17 }, { "created_at": "2015-03-20T12:15:30", "id": 579312, "text": "Rappel: la date limite pour s'inscrire
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views38 pages

OOP2 (Part 7) - Structured Data

Here is the JSON data for the example profile view: { "id": 8839, "name": "Université Antonine", "following": true, "tweets": 1531, "statuses": [ { "created_at": "2015-03-21T17:32:00", "id": 579334, "text": "Bon travail pour vos examens!", "retweet_count": 17 }, { "created_at": "2015-03-20T12:15:30", "id": 579312, "text": "Rappel: la date limite pour s'inscrire
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

OBJECT ORIENTED PROGRAMMING - 2

1 C# Language
STRUCTURED DATA
2
STRUCTURED DATA
3 CONCEPTS AND TERMINOLOGIES
CONCEPTS AND TERMINOLOGIES
○ Markup Languages: Languages used to define and structure the information
contained in a document
● HTML
● XML

○ Tag: basic semantic element of markup languages.


HTML
<h1>Titre 1</h1>
<img src="myImage.png" >
XML
<name>eyrolles</name>
<place>paris</place> 4
STRUCTURED DATA
5 XML
XML
○ XML (EXtensible Markup Language)

○ Structured Markup Languages

XML Document Corresponding Tree


XML
○ XML (EXtensible Markup Language)
○ Structured Markup Language

7
XML
Based on 2 fundamental concepts

○ Separate structure, content and presentation


● To the same content can be associated several formatting

○ Tags are not fixed


● Create tags as needed

8
XML
Consequences of these two concepts: XML is...
○ A document format

● Extension: .xml

○ A data format

○ Used for structuring information

○ A metalanguage
● used to create other markup languages
9
<department deptid=“15”>
XML <deptname>…</deptname>
<employees>
XML vs. SQL <employee>

</employee>
<DEPARTMENTS>
<employee>

</employee>
</employees>
</department>


</DEPARTMENTS>

10
XML
XML vs. HTML
Compared to HTML, the tags in XML:
○ Have a meaning

○ Have a hierarchy
● structured data in tree structure

○ Are extensible
● defining new tags

○ Are intended to store data


11
● and not presenting them
XML
○ A “well-formed” XML document
● Obeys the syntax rules of XML
● Is a prerequisite for validity

○ A “valid” XML document


● Respects all construction rules ("grammar") defined in a DTD / XSD

12
XML
All XML documents:

○ Start with the prologue, which includes:


● The XML declaration
● The declaration of DTD / XSD grammar file

○ Contains the tree of elements


● A root element: a SINGLE element that contains all the others elements
● Elements: may contain text / other elements
13
● Attributes
XML
XML declaration (order of the attributes to be respected):
○ <? xml version = "1.0" encoding = "..." standalone = "yes"?>

● version = version of XML used in the document


● encoding = character encoding set used (default UTF-8)
● standalone = document dependency on a
● grammar
○ "Yes": the application processor does not expect any DTD external to the

document
○ "No": the application processor is expecting an external DTD reference
14
XML
Elements vs. Attributes

○ Use elements when…


● the order is important
● you want to reuse an element several times (with the same parent)
● you want to have descendants / an internal structure
● you want to represent a data type (object) with properties as "attributes”

○ Use attributes when you need to…


● Represent properties of an object (element)
● Identify elements 15
○ Example: <note id="p501”>
XML
Basic Syntax Rules
○ All tags must all be closed

○ All tags without content must end with the characters "/>"

○The names of the start and end tags match exactly and in terms of case
● False: <Parent>Bob</parent>
● False: <Parent>Bob</child>

○Tags must not overlap


● False: <parent> <child>Alice</ parent> </child>
● True: <parent>

<child>Alice</ child> 16

</parent>
<result>a is &lt; b</result>
XML
Basic Syntax Rules
○ Attribute names only appear once for each item Result:
○Attribute values are enclosed in quotes or apostrophes a<b
● <birthday date="2011-01-01">
● <birthday date='2011-01-01'>

○Names of elements can not:


● start with a number or punctuation
● start with the letters xml, or XML ...
● contain spaces

○Avoid certain signs that could lead to confusion like -; . < > 17
● Instead, use predefined entities such as: &lt; &gt; …
XML
CDATA

○ By default, all data is PCDATA (Parsed Character Data): text parsed by a parser
● Tags will be taken in the context of markup
● The entities will be extended

○ CDATA allows you to define a block of characters that should not be parsed by
the XML parser:
● <! [CDATA [Welcome to this course class <XML and Distributed Software
Architecture>]]>

18
XML
Comments
○ Start with <!-- and end with -->

○ Can be placed anywhere - as long as they are outside a tag


○ Examples

● False: <parent <! - this is not correct ->> Bob </ parent>
● True:
● <! - this is correct ->
● <child>Alice <! - this is correct -> </ child>

19
EXERCISE: ARE THE FOLLOWING XML DOCUMENTS WELL-FORMED?
<?xml version=“1.0”?>
<to>Tove</to>
(a) <from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>

<?xml version=“1.0”?>
<note>
(b) <to age=29>Tove</to>
<from>Jani</from>
</note>

<?xml version =“1.0”?> <price>


<Menu> <total>10</total>
<food id=“6”>
<name>strawberry waffles</name>
(c) <currency>usd</currency>
<price curr=“usd”>10</price>
</price>
<description>light waffles covered with strawberries</description> 20
</food>
</Menu>
EXERCISE: ARE THE FOLLOWING XML DOCUMENTS WELL-FORMED?
<?xml version=“1.0”?>
<MyPersonalInformation>
<FullName>Mandrix Mortel Mortini</FullName>
<BirthDate>
<Month>May</Month>
<Date>17</Date>
<Year>1983</Year>
</birthdate>
(d)
<Address>
<Street>St. Michael<Street>
<Province>Palo<Province>
<City>Tacloban<City>
<Country>Philippines<Country>
<PostalCode>6501<PostalCode>
</Address>
</MyPersonalInformation>

21
EXERCISE: ARE THE FOLLOWING XML DOCUMENTS WELL-FORMED?
<?xml version=“1.0”?>
<breakfast menu>
<food price=“5.95” calories=“650” price=“5.90”>
<name>Belgian Waffles</nom>
(e)
<description>two of our famous Belgian Waffles</food>
</description>
</breakfast menu>

<?xml version="1.0"?>
<classe>
<titre>HTML Partie 1
(f) <periode nom="session 1">
<periode nom="session 2">
<periode nom="session 3">
</classe>

22
STRUCTURED DATA
23 JSON
JSON
○ JavaScript Object Notation

○ A data format

○ 2 types of elements
● object: set of key / value pairs
● array of objects

○ Widely used to exchange data across the web

24
JSON
○ Compared to XML, JSON
● Lightweight: used to fetch data from a server
● Higher processing speed

○ Compared to JSON, XML:


● Is more suited for presentation
● Allows the use of attributes
● Allows the creation of namespaces
● Allows extraction (XPath, XQuery, etc.)
● Allows data validation (DTD / XSD grammar)
● Allows transformation into other types of formats (XSLT) 25
JSON
○ JSON vs. XML
<?xml version="1.0"?>
<book id="123"> {
<title>Object Thinking</title> "id": 123,
<author>David West</author> "title": "Object Thinking",
<published> "author": "David West",
<by>Microsoft Press</by> "published": {
<year>2004</year> "by": "Microsoft Press",
</published> "year": 2004
</book> }
}

XML FORMAT JSON FORMAT 26

167 characters 140 characters


JSON
Exercise:

Write the necessary data in JSON format,


assuming that these data will be displayed
in a view similar to the one on the right:

27
JSON
{
"id": 8839,
"name": "Université Antonine",
"following": true,
"tweets": 1531,

"statuses": [
{
"created_at": "2015-03-21T17:32:00",
"id": 579334,
"text": "Bon travail pour vos examens! »,
"retweet_count": 17,
"favorite_count": 1,
},
{
"created_at": "2015-03-21T07:40:10",
"id": 579185,
"text": "Bienvenue à l’Université Antonine.",
"retweet_count": 0,
28
"favorite_count": 25
}
]
STRUCTURED DATA
29 Exercises
EXERCISE 1
○ Structure a "mind map" to elaborate data relevant to a restaurant menu

○ Write the corresponding XML document

30
EXERCISE 2
Write the necessary data that are needed for
display in a view similar to the one on the right:

○ In XML format
○ In JSON format

31
EXERCICE 4 (SOLUTION)
{
<?xml version="1.0" encoding="UTF-8" ?> "users": [{
"id": 1,
<users> "fullname": "Ryan Hopkins",
<user id="1"> "likes": 178,
<fullname>Ryan Hopkins</fullname> "totalPosts": 13,
<likes>178</likes> "totalFollowing": 78,
<totalPosts>13</totalPosts> "totalFollowers": 65,
<totalFollowing>78</totalFollowing> "imageUrl": "http://sample.com/1.jpg",
<totalFollowers>65</totalFollowers> "city": "New York"
<imageUrl>http://sample.com/1.jpg</imageUrl> },
<city>New York</city> {
</user> "id": 2,
<user id="2"> "fullname": "John Doe",
<fullname>John Doe</fullname> "likes": 17,
<likes>17</likes> "totalPosts": 29,
<totalPosts>29</totalPosts> "totalFollowing": 13,
<totalFollowing>13</totalFollowing> "totalFollowers": 100,
<totalFollowers>100</totalFollowers> "imageUrl": "http://sample.com/2.jpg",
<imageUrl>http://sample.com/2.jpg</imageUrl> "city": "Paris"
<city>Paris</city> }
</user> ] 32
</users> }
XML PARSING IN JAVA

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


<root>
<person>
<name>John Doe</name>
<age>30</age>
<city>New York</city>
</person>
<person>
<name>Jane Doe</name>
<age>25</age>
<city>Los Angeles</city>
33
</person>
</root>
XML PARSING IN JAVA

// Specify the path to your XML file


String filePath = "C:\\Users\\akour\\eclipse-workspace\\
XmlParsing\\src\\persons.xml";

DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(filePath);

// Get the root element


Element root = document.getDocumentElement();

NodeList personList = root.getElementsByTagName("person"); 34


XML PARSING AND ITERATING

// Iterate through the list and print information


for (int i = 0; i < personList.getLength(); i++) {
Node personNode = personList.item(i);
if (personNode.getNodeType() == Node.ELEMENT_NODE) {
Element personElement = (Element) personNode;
String name = personElement.getElementsByTagName("name").item(0).getTextContent();
String age = personElement.getElementsByTagName("age").item(0).getTextContent();
String city = personElement.getElementsByTagName("city").item(0).getTextContent();

System.out.println("Person " + (i + 1) + ":");


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
System.out.println();
} 35
}
ADDING NEW ELEMENT AND SAVE IT

private static Element createPersonElement(Document document, String name, String age, String city)
{
Element person = document.createElement("person");

Element nameElement = document.createElement("name");


nameElement.appendChild(document.createTextNode(name));

Element ageElement = document.createElement("age");


ageElement.appendChild(document.createTextNode(age));

Element cityElement = document.createElement("city");


cityElement.appendChild(document.createTextNode(city));

person.appendChild(nameElement);
person.appendChild(ageElement);
person.appendChild(cityElement);
36
return person;
}
ADDING NEW ELEMENT AND SAVE IT

private static void saveDocument(Document document, String filePath)


{
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(filePath);
transformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
37
}
}
THANK YOU!
38 Questions?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy