XML in Firefox 1.5, Part 1: processing XML in Firefox using JavaScript

Source: Internet
Author: User
Tags xslt xslt processor

After learning about the basic display and style of XML in the Firefox browser, the next function to be followed is script. In this article, I will show how to use JavaScriptCodeProcess the basic concept of XML. All the code examples and screens in this article are created and tested using Firefox 1.5.0.4 in Ubuntu Linux. The configuration file has not been modified (that is, there is no extension, and the default options for installation are retained ). If you want to write cross-browser code for XML processing, you may have to use other browser sniffing technologies. However, I have not introduced these technologies in this article.

Load XML files

You can use the JavaScript code embedded in the web page to load XML documents. I will start with an HTML web page example where a simple XML Mailing List format is loaded for dynamic update. the XML document to be loaded is shown in labels. XML in Listing 1 ).

Listing 1. (labels. XML) Address tag XML

<? XML version = "1.0" encoding = "iso-8859-1"?> <Labels> <label id = 'EP' added = "2003-06-10"> <Name> Ezra Pound </Name> <address> <Street> 45 usura place </street> <City> Hailey </city> <province> id </province> </address> </label> <label id = 'tse' added = "2003-06-20"> <Name> Thomas Eliot </Name> <address> <Street> 3 Prufrock Lane </street> <city> Stamford </city> <province> CT </province> </address> </label> <label id = "LH" added = "2004-11-01"> <Name> Langston Hughes </Name> <address> <Street> 10 bridge tunnel </street> <city> Harlem </city> <province> ny </province> </address> </label> <label id = "CO" added = "2004-11-15"> <Name> Christopher okigbo </ name> <address> <Street> 7 Heaven's Gate </street> <city> idoto </city> <province> Anambra </province> </address> </label> </labels>

Listing 2 is an HTML page with only one link. The link displays "Click here to load addresses ". Click the link to add the address tag to the page.

Listing 2. Loading XML using JavaScript on HTML pages for dynamic updates

<! Doctype HTML public "-// W3C // dtd html 4.01 // en" "http://www.w3.org/TR/html4/strict.dtd"> <HTML> 

ScriptElements reflect dynamic features and define a JavaScript functionLoadaddressesThis function will be called by links in HTML. This function creates an empty document instance and then usesLoadFunction read in List 1 (labels. XML ).LoadFunctions are executed asynchronously. Therefore, when the XML document is read, the script can jump to the next line for execution, enabling you to start running with a trigger function after the XML file is loaded. Therefore, I am an independent function.WritelistSetOnloadAttribute. This function uses the Document Object Model (DOM)GetelementsbytagnameMethod to traverse tags. If the XML document uses a namespace, useGetelementsbytagnamensForm instead of the above method, and specify the namespace as the first parameter. In the next section, you will see an example like this. In Listing 2, only the DOM basic layer (DOM level 1) is used for XML processing. For applications that support namespacesProgramYou need to use Dom Level 2. It extends many Level 1 methods and supports namespaces. Listing 2 creates a sub-tree that represents an ordered list and uses the HTML main document as the factory to create nodes. In this way, the generated subtree can be inserted into the main HTML document. Listing 2 reads the source XML tree in normal mode and adds the corresponding node to the output HTML subtree.

For eachLabelElement execution loop statementLabels [I]. childnodes, SearchNameAndAddressSubnode. To avoid operations on child nodes of a text node, useNodetypeTest. UseFirstchild. nodevalueMethod for accessNameChild Text of the element. PairAddressElement, the first child node is a space. You cannot accessAddressAny text content of the subnode. UseGetattributeMethod can access the ID. Add all the collected text to the list items. UseAppendchildMethod to update the HTML document containing the subtree. AvailableUpdatetargetThe ID Flag adds the child tree element (Body). When you load the HTML in Firefox for the first time, you can only see the link shown in Figure 1.

Figure 1. Browser display after listing 2 is loaded
 

Click the link to obtain the latest display immediately, as shown in figure 2.

Figure 2. Load List 2 and click the link to display in the browser
 

Use scripts for XML Main Documents

In the first part of this series, I introduced how to browse XML files in Firefox. To use JavaScript in this case, you need to nest a reference in the script file. The example XML file displayed in listing 3 (designers. XML) is a list of designers. XML references an independent CSS file to display XML, and references an independent Javascript file to create a link element.

Listing 3. (designers. XML) represents the XML format of the fashion designer Link

<? XML version = '1. 0' encoding = 'utf-8'?> <? XML-stylesheet type = "text/CSS" href = "designers.css"?> <Designers> <blurb> <designer homepage = "http://doria.co.uk"> Doria Ltd. </designer> of London </blurb> <designer homepage = "http://samsara.biz"> samsara saris </designer> of Mumbai </blurb> <designer homepage = "http://pcp.co.uk"> pikeman camouflage, PLC. </designer> of London </blurb> <designer homepage = "http://mandalay.co.jp"> Mandalay </designer> of Tokyo </blurb> <XHTML: script xmlns: XHTML = "http://www.w3.org/1999/xhtml" src = "designers. JS "type =" application/JavaScript "/> </designers>

The style sheet Processing Command provides basic instructions for displaying XML. Listing 4 (designers.css) shows CSS.

Listing 4.(designers.css) modifies the CSS displayed in the XML format in listing 3.

* {Display: Inherit;} designers {display: block;} blurb {margin: 1em; width: 20em;} A {display: inline; text-Decoration: none; color: green; Border: thin blue solid;} script {display: none ;}

Style Sheet notifies the browserDesignersAndBlurbAs a block area, and ignoreScriptElement. By linking (AElement) is displayed together with the visible prompt, which makes it easier to identify links. You will notice that the XML source file does not exist.AElement. Therefore, scripts are used here. JavaScript code uses XHTML link elements insteadDesignerElement. The XHTML link element is provided through an XHTML script element. Therefore, any XML can be embedded as long as Firefox is used (of course, you may encounter mode compatibility issues ). Firefox runs the scripts in the loaded documents after they are encountered. Therefore, put the scripts after all the elements to be processed. Listing 5 (designers. JS) shows JavaScript code.

Listing 5. (designers. JS) converts XML elements from listing 3 to scripts with XHTML links

// Save the XHTML namespace for when you need it var xhtmlns = "http://www.w3.org/1999/xhtml "; // get all elements named "blurb" in the document // The first "" indicates no namespace for the element we're re seeking var blurbs = document. getelementsbytagnamens ("", "blurb"); // loop over each element we found for (VAR I = 0; I <blurbs. length; I ++) {// retrieve the blurb element from the collection var blurb = blurbs [I]; // get the designer element within the blurb // assumes only one designer element per blurb var designer = blurb. getelementsbytagnamens ("", "designer "). item (0); // in Dom the text in designer is actually a text Node object child // of blurb. the link title is the value of this text node // assumes the text node is normalized var link_title = designer. firstchild. nodevalue; // link URL is the homepage attribute of designer, in no namespace var link_url = designer. getattributens ("", "Homepage"); // create a new XHTML namespace link element var xhtml_link = document. createelementns (xhtmlns, "A"); // create a new text node with the link title var new_text_node = document. createtextnode (link_title); // set the href attribute to the link URL xhtml_link.setattributens ("", "href", link_url ); // attach the text node with the link title to the XHTML link xhtml_link.appendchild (new_text_node); // Replace the designer element with the new XHTML link element blurb. replaceChild (xhtml_link, designer );}

Because the script in listing 5 supports namespaces (especially XHTML namespaces), I use the DOM method that supports namespaces. Figure 3 shows the result of listing 3. As you can see, the browser immediately applies CSS and scripts.

Figure 3. Load the Browser display in listing 3
 



Back to Top

Call XSLT

Using JavaScript, you can access most browser functions, including the XSLT engine. Listing 6 is a script snippet that executes XSLT conversion.

Listing 6. Load the XML document and XSLT conversion and execute the JavaScript code for the conversion

// Create An XSLT processor instance var processor = new xsltprocessor (); // create an empty XML document for the XSLT transform var transform = document. implementation. createdocument ("", "", null); // load the XSLT transform. onload = loadtransform; transform. load ("display. XSLT "); // triggered once the XSLT document is loaded function loadtransform () {// attach the transform to the processor. importstylesheet (Transform); Source = document. implementation. createdocument ("", "", null); source. load ("source. XML "); source. onload = runtransform;} // triggered once the source document is loaded function runtransform () {// run the transform, creating a fragment output subtree that // can be inserted back into the main page document object (given // In the second argument) var frag = processor. transformtofragment (source, document); // Insert the result subtree into the document, using the target element ID document. getelementbyid ('updatetarget '). appendchild (frag );}

If you want to create the entire output document, instead of creating a subtree inserted to other documents, useTransformtodocumentMethod substitutionTransformtofragmentMethod.



Back to Top

Conclusion

The first is an important Disclaimer: the XML Web scripting language has not been fully standardized. Many of the content involved in this article is not cross-browser standardization. Because this series mainly focuses on Firefox, this article does not introduce the changes that other browsers need to make, but you can continue to learn how to modify them to suit various user interfaces. Cross-browser libraries can be used for XML or even XSLT JavaScript operations. If you cannot develop it specifically for a mozila-based browser, you can use a cross-browser library. When processing web scripts, you must consider accessibility. At the same time, pay attention to the separation of content, processing, and display to avoid embedding the reference in the script at the last moment. In addition, you can save and manage the XML that does not contain such references, and insert these references before the XML is sent to the browser.

Now you know how to load and process an independent XML file in a web script, how to call the script from the XML main document, and how to call the XSLT processor from the script. Because JavaScript supports all browser features, you can use it for more XML processing. You can apply various scripting techniques such as dynamic HTML (DHTML) to XML processing. Ecmascript for XML (E4X) is a set of language enhancements to JavaScript (technically, ecmascript), making XML processing easier. This new standard adds special usage for XML processing. Firefox 1.5 supports E4X.ArticleDescribes it. Without sacrificing the powerful structure of XML, a moderately and well-designed script can present all the charm of modern web applications.

References

Learning

  • For more information, see the original article on the developerworks global website.

  • XML in Firefox 1.5, Part 1: XML feature Overview (September 2005) and XML in Firefox 1st, Part 2: Basic XML Processing (March 2006): review the first two articles in the developworks series.
  • Understand CSS and the basic concepts of displaying XML with CSS. View these Tutorials:
    • Cascading Style Sheets display XML: Use Cascading Style Sheets to display XML, Part 1: Basic Techniques for displaying XML in a web browser (January 1, 1st ).
    • The Cascading Style Sheet displays XML: displays XML using a Cascading Style Sheet, Part 1: displays XML advanced technology in a web browser (January 2nd) this section describes how to use CSS to modify the advanced themes of XML in a browser, including the discussion of script technology.
    • If you are familiar with XSLT, you can directly view the Cascading Style Sheet display XML: Use the Cascading Style Sheet to display XML, Part 1: processing XML in combination with XSLT and CSS (January 3rd) this article discusses the application of XSLT to XML sources, including the use of XSLT technology to process CSS for HTML or XML output.

  • JavaScript and Dom: add these handy Mozilla references as bookmarks.
  • Javascript MIME type: Learn about the complexity of choosing a javascript media type through Anne Van Kesteren's article.
  • Ibm xml 1.1 Certification: Learn How to become an IBM-certified developer of XML 1.1 and related technologies.
  • XML: Visit the developerworks XML area for a wide range of technical articles and tips, tutorials, standards, and IBM redbooks.
  • Developerworks technical activities and network broadcasts: Keep an eye on the latest technological advances.

Obtain products and technologies

    • Firefox: A mozilla-based Web browser that provides standard compliance, high performance, and security, as well as stable XML features. The current version is 1.5.0.4.

Discussion

    • XML Forum: participate in discussions related to XML.

About the author

Uche ogbuji is one of the consultants and creators of fourthought Inc., a software supplier and consulting company specialized in enterprise knowledge management XML solutions. Fourthought developed 4 suite, an open source platform for XML, RDF, and knowledge management applications. Mr. ogbuji is also the main developer of the versa RDF query language. He is a computer engineer and writer born in Nigeria and now lives and works in bord, Colorado, USA. You can use his weblog copia to learn more about Mr. ogbuji.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.