Xml Javascript

  • Uploaded by: anon-506495
  • 0
  • 0
  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Xml Javascript as PDF for free.

More details

  • Words: 1,651
  • Pages: 62
XML and JavaScript Lecture 10

cs193i – Internet Technologies Summer 2004 Stanford University

Administrative Stuff   

Lab #4 due August 9 HW #4 due August 11 Final exam Friday, 8/13  Gates B03  7-10pm 

What is JSP? 

Separate computation from presentation Presentation: JSP  Computation: Servlet 





 

Mostly HTML page, with extension .jsp Include JSP tags to enable dynamic content creation Translation: JSP → Servlet class

A JSP File

Expression Language 

Makes syntax short and readable, like JavaScript 



Arithmetic 



${4.0 >= 3} → true

Implicit Objects  



${1.2 + 2.3} → 3.5

Comparisons 



${expression}

${param.foo} → JSP 2.0 ${param["foo"]} → JSP 2.0

Functions 

${my:reverse(my:reverse(param["foo"]))} → JSP 2.0

EL Examples 

  

${order.amount + 5} ${order['amount'] + 5}

XML  

XML → Extensible Markup Language Just a text file, with tags, attributes, free text... looks much like HTML

Purpose 



Used to create special-purpose markup languages Facilitates sharing of structured text and information across the Internet.

XML Describes Data 

DTD -- formal description of the class of XML document your file adheres to (like file extension) 





Buzzword: DTD is one way to describe XML "Schema" (grammar). There are other ways...

XML Structure Facilitates Parsing of Data Two Apps still have to agree on what the meaning of the "descriptive tags"

XML Nested Tags 



Like a tree, each element is contained inside a parent element Each element may have any number of attributes







pages=“30”

<para>… This is some text!






Apple Safari Bookmarks

Property List Editor

Apple Bookmarks

Document Data Type

XML Structure 

Nested Tags 



Empty Tags 





Attributes -- Variable Value Bindings in the Tag 



Here's some text surrounded by tags

<dot x="72" y="13"/>

Free Text 

<dot x="1" y="1">I'm free!!!

Special Characters     

< > & " '

< > & " '

Organization Strategies 

XML Text -- blocks of free text with tags to mark sections And here is some text



XML Tree -- nested tags, only leafnodes have free text

XML Tree Hans Gruber 123456 <username>hans

Sub-Tags vs. Attributes 

Sub-Tags <dot> <x>13 57



Attributes <dot x="13" y="57"/>

When to use Attributes  

Whenever Possible Sub-Data is short & simple, and doesn't repeat <dot x="13" y="56"/>



NOT: <dots x1="13" y1="56" x2="14“ y2="67 x3="56" y3="100" ... />

When to use Tags 





<parent> ... ... ... <dots> <dot x="13" y="15"/> <dot x="1" y="3"/> ... <description>This is a super long description that should be put between tags, as opposed to in an attribute...

XML Example - Dots Meaning <dots> (1, 2) <dot x="1" y="2" /> (3, 4) <dot x="3" y="4" /> (6, 5) <dot x="5" y="6" /> (7, 8) <dot x="7" y="8" /> (9, 10) <dot x="9" y="10" />

XML and Java  

http://java.sun.com/xml/index.jsp Java API for XML... Binding (JAXB) -- for working w/ Schemas  Processing (JAXP) -- for Parsing! 

JAXP Parsing Strategies 

SAX -- Simple API for XML 



Simple Parser

DOM -- Document Object Model 

Represent XML Doc as Tree of Nodes in Memory

http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPIntro.html

SAX 



Subclass DefaultHandler Implement Notification Methods ("Callbacks") 





startElement(...) // handles open tag endElement(...) // handles close tag characters(...) // handles stuff in

http://sax.sourceforge.net/

mydots.xml <dots> <dot x="81" y="67" /> <dot x="175" y="122" /> <dot x="175" y="122" /> <dot x="209" y="71" /> <dot x="209" y="71" /> <dot x="133" y="877">My Favorite Dot! <dot x="1" y="2"/>

SAX Example SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); saxParser.parse( new BufferedInputStream(new FileInputStream( new File(argv[0]))), new XMLDotReader());

XMLDotReader Class • Maintains flip state in boolean • extends DefaultHandler • overrides startElement(...) • Check if dot tag or flip tag • Do stuff, accordingly • overrides endElement(...) • If flip tag... "unflip"

DOM  





Get a DocumentBuilder Read in an XML File, get a Document object Traverse the Document object and do stuff http://java.sun.com/j2ee/1.4/docs/tutorial/ doc/JAXPDOM.html#wp79996

DOM Example // Step 1: create a DocumentBuilderFactory // and setNamespaceAware DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); // Step 2: create a DocumentBuilder DocumentBuilder db = dbf.newDocumentBuilder();

// Step 3: parse the input file to get a Document object Document doc = db.parse(new File(filename)); Node n = (Node) doc; ... int type = n.getNodeType(); for (Node child = n.getFirstChild(); child!=null; child=child.getNextSibling()) { ... } ttp://java.sun.com/developer/earlyAccess/xml/examples/DOMEcho/DOMEcho.jav

SAX vs. DOM 

SAX -- Event Driven, Serial Access, Element by Element 



Preferred for Server Side Apps

DOM -- Read in whole XML structure, CPU & memory intensive 

Ideal for interactive apps (Thick Clients); allows interactive editing of XML structure in memory

Other Java Parsers 

There are other free parsers out there, that use either SAX or DOM strategies... “nanoxml”  “JDOM” 

XML Uses 

Config Files 



Data Files 



Apple Property List SVG

Messages 

SOAP

Strengths and Weaknesses 

  



Strengths Just Text: Compatible with Web/Internet Protocols Human + Machine Readable Represents most CS datastructures well Strict Syntax → Parsing Fast and

 

Weaknesses Verbose/Redundan t Trouble modeling overlapping data structures (non hierarchical)

Five Minute Break

JavaScript 





Invented by Netscape Communications Cross Platform, Object-based, Scripting Language ECMAScript (ECMA-262)

JavaScript HTTP Request

Client runs JavaScript

HTTP Response HTML file with embedded JavaScript

JavaScript  

All Client Side Can Adjust HTML  Open Windows, Resize Windows  Animations, Play Sounds 



Cannot Access File System  Do Networking 

JavaScript 

Advantages 



Better User Experience (2X Latency)

Disadvantages Thicker Client  Possible Abuse 

JavaScript Basics 



<script> section in HTML runs on document load No type declarations 



undefined if not given a value

Global variables by default 

var makes them local

Generate Dynamic HTML ... ...Regular HTML Here.... <SCRIPT TYPE="text/javascript"> ...More Regular HTML....

JavaScript and Browser  

  

document – HTML document document.name – named element in document document.images – array of images document.forms – array of forms Ways to access window, cookies, etc.

document.write(“String” ) <TITLE>Hello!

First JavaScript Page

<SCRIPT TYPE="text/javascript"> "); document.write("Hello WWW!"); document.write("
"); //-->

document.write(“String” )

document.write(“String” ) <TITLE>Hello! <SCRIPT TYPE="text/javascript"> none"); } else { return(document.referrer); } } //-->

Extracting Info!

<SCRIPT TYPE="text/javascript"> "); document.writeln("
  • " + document.location); document.writeln("
  • “ + referringPage()); document.writeln("
  • " + navigator.appName); document.writeln(""); //-->

    document.write(“String” )

    Monitor User Events 



    function dontClick() { alert("I told ya not to click!"); }

    Monitor User Events

    www.devguru.com

    DOM  



    JavaScript is Object-Oriented JavaScript Interacts with Document Object Model of Browser DOM Not Totally Standardized

    Objects

    http://www.devguru.com

    Arrays or Objects?   

    The Same! a.foo <=> a["foo"] <=> a[x] a[2] cannot be accessed as a.2

    Global Functions   



    escape(string) unescape(string) Safe Strings ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 1234567890 @*-_+./ Unsafe Strings => %20, %5c, etc...

    Communicating with User  



    Alert window.alert("Hello!"); Confirm window.confirm("Delete files? =D") Status Bar window.status = "Hi!";

    JS Demo <script language="JavaScript"> function hello(greeting) { var str = greeting + "!!!"; alert(str); } count = 0; function upCount() { count++; alert(count); } function noFear() { var fear = document.affirm.fear.value; if (!document.affirm.mockMode.checked) { alert("No " + fear + " to be seen around here!"); } else { var mock = "Being afraid of " + fear + " is stupid!"; window.status = mock document.affirm.mock.value = mock; } }



    oops

    Thing you are afraid of...

    Mock mode:



    Fear Example

    Quotes Example 

    Text Box
    Search:




    Text Box

    <script language="JavaScript"> // We allocate a global array and fill it with the quote data. lines = new Array(); lines.push("Everybody's always telling me one thing and out the other."); lines.push("Even a fish could stay out of trouble if it would just learn to keep its mouth shut."); lines.push("Beware the lollipop of mediocrity -- lick it once and you suck forever."); lines.push("We don't have time to stop for gas -- we're already late."); lines.push("By doing just a little each day, I can gradually let the task overwhelm me."); lines.push("Being powerful is like being a lady. If you have to tell people you are, you aren't."); lines.push("Never attribute to malice that which can satisfactorily be explained by incompetence.");

    // Search for an element with the given id and set its innerHTML to // the given text. function setText(id, text) { var node = document.getElementById(id); if (node != null) { node.innerHTML = text; //node.childNodes[0].data = text; // alternative for some simple tags } } // Given the name of a form, access the target field within that // form and using its target text, generate the quote list and put // it into the result tag. function setQuotes(form_name) { // cute: use [] instead of . to access the form by name var target = document[form_name].target.value; var contents = ""; target = target.toLowerCase(); for (var i in lines) { if (lines[i].toLowerCase().indexOf(target)!=-1) { contents = contents + "
  • " + lines[i] + "\n"; } } setText("result", contents); }

    JavaScript Summary 

    Good For Simple Things 



    Bad when Abused 



    Save RT Latency Popups!!!

    Don't Always Rely on It 

    DOMs not standardized

  • Related Documents

    Xml Javascript
    November 2019 9
    Javascript E Xml
    October 2019 14
    Xml
    June 2020 21