firefo xml 读写实现js代码
一 读xml文件到字符串
第一步:将xml文件,转化为DOM结构
1
var xmlDoc = document.implementation.createDocument("", "test", null);
xmlDoc.load("d:\\develop\\bookmarks.xml");
2
var req = new XMLHttpRequest();
req.open("GET", "chrome://passwdmaker/content/people.xml", false);
req.send(null);
var dom = req.responseXML;
dom就是DOM结构对象
第二步:将DOM结构转化为xml字符串
var serializer = Components.classes["@mozilla.org/xmlextras/xmlserializer;1"].createInstance(Components.interfaces.nsIDOMSerializer);
var str = serializer.serializeToString(dom);
str就是xml内容的字符串
二 将xml字符串写成xml文件
// str为xml字符串
var parser = new DOMParser();
var dom = parser.parseFromString(str, "text/xml");
var serializer = Components.classes["@mozilla.org/xmlextras/xmlserializer;1"].createInstance(Components.interfaces.nsIDOMSerializer);
var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream);
var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("d:\\develop\\myxmlfile.xml");// 保持的位置
foStream.init(file, 0x02 | 0x08 | 0x20, 0664, 0); // write, create, truncate
serializer.serializeToStream(dom.documentElement, foStream, ""); // rememeber, dom is the DOM tree
foStream.close();
附件:
1 创建DOM结构
// 生成document对象
var xmldoc = document.implementation.createDocument("","",null);
// 创建xml文件的头
// <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
var head = xmldoc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"");
xmldoc.appendChild(head);
// 创建ROOT节点
var nodest = xmldoc.createElement("nodeset");
xmldoc.appendChild(nodest);
// 创建子节点
var elem1 = doc.createElement("name");
elem1.textContent = "张三";
nodest.appendChild(elem1);
var elem2 = doc.createElement("name");
elem2.textContent = "李四";
nodest.appendChild(elem2);
// 创建的结果如下
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><nodeset><name>张三</name><name>李四</name></nodeset>
这样生成的xmlDOM结构通过系列化转化为xml字符串时不会自动缩进,但通过XML对象解析下就可以了。
var serializer = Components.classes["@mozilla.org/xmlextras/xmlserializer;1"].createInstance(Components.interfaces.nsIDOMSerializer);
// 解析DOMxml结构到xml字符串
// 要XML对象解析成功必须将xml头去掉
// 去掉xml头
var xmlDeclaration = /^<\?xml version[^>]+?>/;
var str = new XML( serializer.serializeToString(xmldoc).replace(xmlDeclaration, '') ).toXMLString();
哈哈,现在的str就是能够自动缩进的xml字符串了。不过要是你的xml要编码成功还得在str前面加上xml头,千万别忘了啊。