在Javascript中创建XML [英] Create XML in Javascript
问题描述
我想知道,是否可以在Javascript中创建包含一些数据的XML文件?我将数据存储在变量中。
I'm wondering, is it possible to create an XML file with some data in Javascript? I have the data stored in variables.
我用Google搜索了一下,看起来好像没什么好说的。我以为我可以使用 XMLWriter
,例如:
I've googled around a bit and it doesn't seem like it's talked about much. I thought i could use XMLWriter
such as this:
var XML = new XMLWriter();
XML.BeginNode ("testing");
XML.Node("testingOne");
XML.Node("TestingTwo");
XML.Node("TestingThree");
XML.EndNode();
如本教程所述: EHow教程
然而,当我执行此代码时,我收到以下错误:
However, when i execute this code i get the following error:
ReferenceError: XMLWriter is not defined
关于我如何开始这个的任何想法?
Any ideas on how i can get started with this?
提前致谢!
推荐答案
免责声明:以下答案假定您使用的是Web浏览器的JavaScript环境。
JavaScript使用XML DOM对象处理XML。
您可以通过三种方式获得此类对象:
JavaScript handles XML with 'XML DOM objects'. You can obtain such an object in three ways:
1。创建新的XML DOM对象
var xmlDoc = document.implementation.createDocument(null, "books");
第一个参数可以包含要创建的文档的名称空间URI,如果文档属于一个。
The first argument can contain the namespace URI of the document to be created, if the document belongs to one.
来源: https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument
2。使用XMLHttpRequest获取XML文件
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var xmlDoc = xhttp.responseXML; //important to use responseXML here
}
xhttp.open("GET", "books.xml", true);
xhttp.send();
3。解析包含序列化XML的字符串
var xmlString = "<root></root>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml"); //important to use "text/xml"
获得XML DOM对象后,可以使用方法来操作它,如
When you have obtained an XML DOM object, you can use methods to manipulate it like
var node = xmlDoc.createElement("heyHo");
var elements = xmlDoc.getElementsByTagName("root");
elements[0].appendChild(node);
如需完整参考,请参阅 http://www.w3schools.com/xml/dom_intro.asp
For a full reference, see http://www.w3schools.com/xml/dom_intro.asp
注意:
重要的是,你不要使用文档命名空间提供的方法,i。 e。
Note: It is important, that you don't use the methods provided by the document namespace, i. e.
var node = document.createElement("Item");
这将创建HTML节点而不是XML节点,并将导致节点具有小写标签名称。与HTML标记名称相比,XML标记名称区分大小写。
This will create HTML nodes instead of XML nodes and will result in a node with lower-case tag names. XML tag names are case-sensitive in contrast to HTML tag names.
您可以像这样序列化XML DOM对象:
You can serialize XML DOM objects like this:
var serializer = new XMLSerializer();
var xmlString = serializer.serializeToString(xmlDoc);
这篇关于在Javascript中创建XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!