Javascript загрузка из xml

Read XML file using javascript

You can use below script for reading child of the above xml. It will work with IE and Mozila Firefox both.

  

The code below will convert any XMLObject or string to a native JavaScript object. Then you can walk on the object to extract any value you want.

/** * Tries to convert a given XML data to a native JavaScript object by traversing the DOM tree. * If a string is given, it first tries to create an XMLDomElement from the given string. * * @param source The XML string or the XMLDomElement prefreably which containts the necessary data for the object. * @param [includeRoot] Whether the "required" main container node should be a part of the resultant object or not. * @return The native JavaScript object which is contructed from the given XML data or false if any error occured. */ Object.fromXML = function( source, includeRoot ) < if( typeof source == 'string' ) < try < if ( window.DOMParser ) source = ( new DOMParser() ).parseFromString( source, "application/xml" ); else if( window.ActiveXObject ) < var xmlObject = new ActiveXObject( "Microsoft.XMLDOM" ); xmlObject.async = false; xmlObject.loadXML( source ); source = xmlObject; xmlObject = undefined; >else throw new Error( "Cannot find an XML parser!" ); > catch( error ) < return false; >> var result = <>; if( source.nodeType == 9 ) source = source.firstChild; if( !includeRoot ) source = source.firstChild; while( source ) < if( source.childNodes.length ) < if( source.tagName in result ) < if( result[source.tagName].constructor != Array ) result[source.tagName] = [result[source.tagName]]; result[source.tagName].push( Object.fromXML( source ) ); >else result[source.tagName] = Object.fromXML( source ); > else if( source.tagName ) result[source.tagName] = source.nodeValue; else if( !source.nextSibling ) < if( source.nodeValue.clean() != "" ) < result = source.nodeValue.clean(); >> source = source.nextSibling; > return result; >; String.prototype.clean = function() < var self = this; return this.replace(/(\r\n|\n|\r)/gm, "").replace(/^\s+|\s+$/g, ""); >

Источник

Parsing and serializing XML

At times, you may need to parse XML content and convert it into a DOM tree, or, conversely, serialize an existing DOM tree into XML. In this article, we’ll look at the objects provided by the web platform to make the common tasks of serializing and parsing XML easy.

Serializes DOM trees, converting them into strings containing XML.

Constructs a DOM tree by parsing a string containing XML, returning a XMLDocument or Document as appropriate based on the input data.

Loads content from a URL; XML content is returned as an XML Document object with a DOM tree built from the XML itself.

A technology for creating strings that contain addresses for specific portions of an XML document, and locating XML nodes based on those addresses.

Creating an XML document

Using one of the following approaches to create an XML document (which is an instance of Document ).

Parsing strings into DOM trees

This example converts an XML fragment in a string into a DOM tree using a DOMParser :

const xmlStr = 'hey!'; const parser = new DOMParser(); const doc = parser.parseFromString(xmlStr, "application/xml"); // print the name of the root element or error message const errorNode = doc.querySelector("parsererror"); if (errorNode)  console.log("error while parsing"); > else  console.log(doc.documentElement.nodeName); > 

Parsing URL-addressable resources into DOM trees

Using XMLHttpRequest

Here is sample code that reads and parses a URL-addressable XML file into a DOM tree:

const xhr = new XMLHttpRequest(); xhr.onload = () =>  dump(xhr.responseXML.documentElement.nodeName); >; xhr.onerror = () =>  dump("Error while getting XML."); >; xhr.open("GET", "example.xml"); xhr.responseType = "document"; xhr.send(); 

The value in the xhr object’s responseXML field is a Document constructed by parsing the XML.

If the document is HTML, the code shown above will return a Document . If the document is XML, the resulting object is actually a XMLDocument . The two types are essentially the same; the difference is largely historical, although differentiating has some practical benefits as well.

Note: There is in fact an HTMLDocument interface as well, but it is not necessarily an independent type. In some browsers it is, while in others it is an alias for the Document interface.

Serializing an XML document

Given a Document , you can serialize the document’s DOM tree back into XML using the XMLSerializer.serializeToString() method.

Use the following approaches to serialize the contents of the XML document you created in the previous section.

Serializing DOM trees to strings

First, create a DOM tree as described in How to Create a DOM tree. Alternatively, use a DOM tree obtained from XMLHttpRequest .

To serialize the DOM tree doc into XML text, call XMLSerializer.serializeToString() :

const serializer = new XMLSerializer(); const xmlStr = serializer.serializeToString(doc); 

Serializing HTML documents

If the DOM you have is an HTML document, you can serialize using serializeToString() , but there is a simpler option: just use the Element.innerHTML property (if you want just the descendants of the specified node) or the Element.outerHTML property if you want the node and all its descendants.

const docInnerHtml = document.documentElement.innerHTML; 

As a result, docInnerHtml is a string containing the HTML of the contents of the document; that is, the element’s contents.

You can get HTML corresponding to the and its descendants with this code:

const docOuterHtml = document.documentElement.outerHTML; 

See also

Found a content problem with this page?

This page was last modified on Jul 4, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Read XML File using Javascript from a Local Folder

My problem is in reading the XML file. All of the examples I have found I think will only work if there is a web server running, which I have to avoid.

7 Answers 7

If you’re reading another file the only way to do that with front end JS is another request (ajax). If this were node.js it would be different because node can access the filesystem. Alternatively if you get the xml into a javascript string on the same page, you can manipulate it. There are a number of good libraries (jquery’s parseXML).

yes, they are, but you can’t have both. If you run an html file with a script in it, that file can’t be an xml file also. You could have some xml in a javascript variable, though. The point I was making was that you can’t load another file w/o ajax

So, I might be a little late to the party, but this is to help anybody else who’s been ripping his/her hair out looking for a solution to this.

First of all, CORS needs to be allowed in the browser if you’re not running your HTML file off a server. Second, I found that the code snippets most people refer to in these kind of threads don’t work for loading local XML-files. Try this (example taken from the official docs):

var xhr = new XMLHttpRequest(); xhr.open('GET', 'file.xml', true); xhr.timeout = 2000; // time in milliseconds xhr.onload = function () < // Request finished. Do processing here. var xmlDoc = this.responseXML; // ; xhr.ontimeout = function (e) < // XMLHttpRequest timed out. Do something here. >; xhr.send(null); 

The method (1st arg) is ignored in xhr.open if you’re referring to a local file, and async (3rd arg) is true by default, so you really just need to point to your file and then parse the result! =)

Источник

Читайте также:  Виртуальная среда программирования питон
Оцените статью