在 Javascript 中创建 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14340894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create XML in Javascript
提问by BigBug
I'm wondering, is it possible to create an XML file with some data in Javascript? I have the data stored in variables.
我想知道,是否可以用 Javascript 中的一些数据创建一个 XML 文件?我将数据存储在变量中。
I've googled around a bit and it doesn't seem like it's talked about much. I thought i could use XMLWritersuch as this:
我在谷歌上搜索了一下,似乎没有谈论太多。我以为我可以XMLWriter这样使用:
var XML = new XMLWriter();
XML.BeginNode ("testing");
XML.Node("testingOne");
XML.Node("TestingTwo");
XML.Node("TestingThree");
XML.EndNode();
as stated in this tutorial:EHow Tutorial
如本教程所述: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?
关于我如何开始这个的任何想法?
Thanks in advance!
提前致谢!
回答by Seb3736
Disclaimer: The following answer assumes that you are using the JavaScript environment of a web browser.
免责声明:以下答案假定您使用的是 Web 浏览器的 JavaScript 环境。
JavaScript handles XML with 'XML DOM objects'. You can obtain such an object in three ways:
JavaScript 使用“XML DOM 对象”处理 XML。您可以通过三种方式获得这样的对象:
1. Creating a new XML DOM object
1. 创建一个新的 XML DOM 对象
var xmlDoc = document.implementation.createDocument(null, "books");
The first argument can contain the namespace URI of the document to be created, if the document belongs to one.
如果文档属于某个文档,则第一个参数可以包含要创建的文档的命名空间 URI。
Source: https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument
来源:https: //developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument
2. Fetching an XML file with XMLHttpRequest
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. Parsing a string containing serialized XML
3. 解析包含序列化 XML 的字符串
var xmlString = "<root></root>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml"); //important to use "text/xml"
When you have obtained an XML DOM object, you can use methods to manipulate it like
当您获得一个 XML DOM 对象时,您可以使用方法来操作它,例如
var node = xmlDoc.createElement("heyHo");
var elements = xmlDoc.getElementsByTagName("root");
elements[0].appendChild(node);
For a full reference, see http://www.w3schools.com/xml/dom_intro.asp
有关完整参考,请参阅http://www.w3schools.com/xml/dom_intro.asp
Note: It is important, that you don't use the methods provided by the document namespace, i. e.
注意:重要的是,不要使用文档命名空间提供的方法,即
var node = document.createElement("Item");
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.
这将创建 HTML 节点而不是 XML 节点,并且会生成一个带有小写标记名称的节点。与 HTML 标签名称相比,XML 标签名称区分大小写。
You can serialize XML DOM objects like this:
您可以像这样序列化 XML DOM 对象:
var serializer = new XMLSerializer();
var xmlString = serializer.serializeToString(xmlDoc);
回答by kkk
Consider that we need to create the following XML document:
考虑我们需要创建以下 XML 文档:
<?xml version="1.0"?>
<people>
<person first-name="eric" middle-initial="H" last-name="jung">
<address street="321 south st" city="denver" state="co" country="usa"/>
<address street="123 main st" city="arlington" state="ma" country="usa"/>
</person>
<person first-name="jed" last-name="brown">
<address street="321 north st" city="atlanta" state="ga" country="usa"/>
<address street="123 west st" city="seattle" state="wa" country="usa"/>
<address street="321 south avenue" city="denver" state="co" country="usa"/>
</person>
</people>
we can write the following code to generate the above XML
我们可以编写下面的代码来生成上面的XML
var doc = document.implementation.createDocument("", "", null);
var peopleElem = doc.createElement("people");
var personElem1 = doc.createElement("person");
personElem1.setAttribute("first-name", "eric");
personElem1.setAttribute("middle-initial", "h");
personElem1.setAttribute("last-name", "jung");
var addressElem1 = doc.createElement("address");
addressElem1.setAttribute("street", "321 south st");
addressElem1.setAttribute("city", "denver");
addressElem1.setAttribute("state", "co");
addressElem1.setAttribute("country", "usa");
personElem1.appendChild(addressElem1);
var addressElem2 = doc.createElement("address");
addressElem2.setAttribute("street", "123 main st");
addressElem2.setAttribute("city", "arlington");
addressElem2.setAttribute("state", "ma");
addressElem2.setAttribute("country", "usa");
personElem1.appendChild(addressElem2);
var personElem2 = doc.createElement("person");
personElem2.setAttribute("first-name", "jed");
personElem2.setAttribute("last-name", "brown");
var addressElem3 = doc.createElement("address");
addressElem3.setAttribute("street", "321 north st");
addressElem3.setAttribute("city", "atlanta");
addressElem3.setAttribute("state", "ga");
addressElem3.setAttribute("country", "usa");
personElem2.appendChild(addressElem3);
var addressElem4 = doc.createElement("address");
addressElem4.setAttribute("street", "123 west st");
addressElem4.setAttribute("city", "seattle");
addressElem4.setAttribute("state", "wa");
addressElem4.setAttribute("country", "usa");
personElem2.appendChild(addressElem4);
var addressElem5 = doc.createElement("address");
addressElem5.setAttribute("street", "321 south avenue");
addressElem5.setAttribute("city", "denver");
addressElem5.setAttribute("state", "co");
addressElem5.setAttribute("country", "usa");
personElem2.appendChild(addressElem5);
peopleElem.appendChild(personElem1);
peopleElem.appendChild(personElem2);
doc.appendChild(peopleElem);
If any text need to be written between a tag we can use innerHTML property to achieve it.
如果需要在标签之间写入任何文本,我们可以使用 innerHTML 属性来实现。
Example
例子
elem = doc.createElement("Gender")
elem.innerHTML = "Male"
parent_elem.appendChild(elem)
For more details please follow the below link. The above example has been explained there in more details.
欲了解更多详情,请点击以下链接。上面的例子已经在那里更详细地解释了。
https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/How_to_create_a_DOM_tree
https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/How_to_create_a_DOM_tree
回答by elad gasner
this work for me..
这对我有用..
var xml = parser.parseFromString('<?xml version="1.0" encoding="utf-8"?><root></root>', "application/xml");
回答by qant
xml-writer(npm package)I think this is the good way to create and write xml file easy. Also it can be used on server side with nodejs.
xml-writer(npm package)我认为这是轻松创建和编写 xml 文件的好方法。它也可以在服务器端与 nodejs 一起使用。
var XMLWriter = require('xml-writer');
xw = new XMLWriter;
xw.startDocument();
xw.startElement('root');
xw.writeAttribute('foo', 'value');
xw.text('Some content');
xw.endDocument();
console.log(xw.toString());
回答by srijan
Only works in IE
仅适用于 IE
$(function(){
var xml = '<?xml version="1.0"?><foo><bar>bar</bar></foo>';
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xml);
alert(xmlDoc.xml);
});
Then push xmlDoc.xml to your java code.
然后将 xmlDoc.xml 推送到您的 java 代码。
回答by metadings
Simply use
只需使用
var xmlString = '<?xml version="1.0" ?><root />';
var xml = jQuery.parseXML(xml);
It's jQuery.parseXML, so no need to worry about cross-browser tricks. Use jQuery as like HTML, it's using the native XML engine.
它是jQuery.parseXML,所以无需担心跨浏览器的技巧。像使用 HTML 一样使用 jQuery,它使用原生 XML 引擎。
回答by user3051040
Your code is referencing this library
您的代码正在引用此库
You can include it, and then your code in question should run as is. If you want to do this without prepending the library & build it with builtin functions only - follow answer from @Seb3736.
您可以包含它,然后您的相关代码应按原样运行。如果您想在不预先添加库并仅使用内置函数构建它的情况下执行此操作 - 请遵循@Seb3736 的回答。
In Browser Example
在浏览器示例中
<html>
<head>
<script src="Global.js" language="javascript"></script>
<script src="XMLWriter.js" language="javascript"></script>
<script language="javascript" type="text/javascript">
function genXML(){
var XML = new XMLWriter();
XML.BeginNode ("testing");
XML.Node("testingOne");
XML.Node("TestingTwo");
XML.Node("TestingThree");
XML.EndNode();
//Do something... eg.
console.log(XML.ToString); //Yes ToString() not toString()
}
</script>
</head>
<body>
<input type="submit" value="genXML" onclick="genXML();">
</body>
</html>

