Массив javascript из xml

XML Parser for JavaScript — xml2array()

xml2array() parses the given XML document and return the data in an associative array.

Useage

XmlHttp.onreadystatechange = function() < if(XmlHttp.readyState == 4 && XmlHttp.status == 200) < var arr = xml2array(XmlHttp.responseXml); // Do what you want with 'arr' >>);

Just load the XML file using the method you are most comfortable with and then call the xml2array function with the XML object as the argument.

Code

The code is given in the xml2array.js file. It is a bit ugly — but it gets the job done. This file also includes the code for the xjx library and the dump function(Javascript equivalent of PHP’s print_r function).

The code is somewhat big(100 lines of code) so I am not putting it in this page — just have a look at the js file for the code. You need just the xml2array() function and the two global variables at top — there are two other functions there — just ignore them.

Problems

There are some problems with the script — but this just the first release so it is to be expected.

I have only tested the script in the following browsers. Please let me know how the script worked in other browser’s.

  • Firefox 1.5 in Linux
  • Firefox 1.5 in Windows
  • IE 6 in Windows
  • Mozilla in Linux

Another problem is that the scripts runs into trouble when such details like XML version( ) or stylesheet information( ) or some other extra infomation like is there in the XML file. I am hopping this will not be much of a problem as this script is aimed for use with Ajax responses in XML format — so we can safely assume that there will not be any ‘stylesheet’ information in it ;-). If you find any solution for this problem, please let me know — my email is moc.liamg@avynnib (Reverse this text to get my Email address)

Actionscript

I was hoping that I could get this script to work in Actionscript. I don’t ‘know’ actionscript per se — I know javascript and assume that I could code in Actionscript as they have very similar syntax. Unfortunately, the script fails in Actionscript — some problem with the whitespace Regular Expression. If any of you know actionscript, please take a look at the script and if you could get it working in Flash, drop me a line at moc.liamg@avynnib (Reverse this text to get my Email address) .

Читайте также:  None text html squid

License

This script is released in the BSD license.

Источник

Convert XML to JavaScript Object

ConvertSimple.com

Use this XML to JavaScript Object converter tool by pasting or uploading XML in the left box below. Results will appear in the box on the right.

How to use XML to JavaScript Object Conversion Tool

  1. Paste your XML input into the left input box and it will automatically convert it into JavaScript Object.
  2. The JavaScript Object output is the box to the right.
  3. If there are any errors in the XML and the converter isn’t able to do the conversion, the error message will appear in the output box letting you know where the error was found in the XML.
  4. Use the control box to select options that will affect the conversion.
  5. Your XML data is secure. ConvertSimple’s converter does not send your XML data to our servers for conversion, the process is done completely in your web browser. That’s what makes ConvertSimple’s converter the safest and fastest converter out there.

XML Format

Name XML
Full form name Extensible Markup Language
File extension .xml
Type of format Markup Language
MIME type application/xml, text/xml

JavaScript Format

Name JavaScript
Full form name JavaScript
File extension .js
Type of format Programming Language
MIME type text/javascript, application/javascript

Источник

Как конвертировать документ xml в массив JavaScript?

День добрый!
Возможно ли документ xml преобразовать в массив JS средствами JavaScript?
Вижу советы в Гугле о конвертации xml в json и дальнейшей работе уже с json. А сразу в обычный масссив можно?

Как можно с помощью библиотеки OpenXML конвертировать документ DOCX в document.XML и обратно
Добрый день! Интересует, как можно с помощью библиотеки OpenXML конвертировать документ DOCX.

Как на JavaScript преобразовать документ XML в формат JSON?
Добрый день, подскажите, пожалуйста, имеется ли такая возможность у javaScript? Есть файл в формате.

Как в netbeans создать javascript, html, xml документ а не только php
Здравствуйте, знаю что тема не в нужном разделе. Подскажите как настроить программу netbeansIDE.

Как добавить узел в документ XML не загружая в память весь документ
Вот собственно вопрос сейчас использую XDocument. То есть формирую узел XElement, добавляю его в.

ЦитатаСообщение от Fatmarmelad Посмотреть сообщение

ЦитатаСообщение от Fatmarmelad Посмотреть сообщение

Вижу советы в Гугле о конвертации xml в json и дальнейшей работе уже с json. А сразу в обычный масссив можно?

Читайте также:  Tf cpp min log level

JSON содержит данные о документе, поэтому приняв определенные правила, по которым документ проецируется на этот формат, можно написать универсальный код, который будет работать с любым хмл, при этом будет получен жсон определенной структуры. То, о чем спрашиваешь ты — в принципе не очень понятно. Ну вот, тебе пример получения массива из хмл.

1 2 3 4 5 6 7 8 9 10 11 12 13
let xtext = `xml version="1.0"?> numbers> number>1number> number>2number> number>3number> number>4number> number>5number> numbers>`; let parser = new DOMParser(); let xdoc = parser.parseFromString(xtext, "text/xml"); let arr = [. xdoc.querySelectorAll("number")].map(v => +v.textContent); console.log(arr);

Я вот только сомневаюсь, что это сильно поможет решить твою конкретную проблему. Просто потому, что хмл может содержать очень разные данные, да и массив тоже. Поэтому, если хочешь чего-то конкретного, то и структуру документа опиши и что хочешь из него получить.

XML/XSL — как конвертировать формат xml в QIF?
Добрый день! подскажите пжл программу, с помощью которой можно конвертировать екселевскую.

Как конвертировать документ word в pdf
Добрый день, не могу понять как конвертировать документ word в pdf при создании документа Word .

Как конвертировать документ в PDF, который будет читаться только на моем компьютере?
Доброго времени суток. Подскажите, пожалуйста, как создать документ большая часть которого будет.

Как конвертировать MS Word в XML
Как конвертировать MS Word в XML используя или какой то JAR file или что нибуть другое?

Как конвертировать формат xml в QIF?
Добрый день! подскажите пжл программу, с помощью которой можно конвертировать екселевскую.

Источник

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.

Источник

Оцените статью