我正在尝试使用JavaScript在Firefox插件中构建一些XML并面临问题。
以下是我正在寻找的XML格式:
<testing>
<testingOne attr="my_attrib">
<TestingTwo>abc</TestingTwo >
<TestingThree>bbc</TestingThree>
</testingOne >
</testing>
我尝试使用下面的代码。但是,它没有用。
var XML = document.createElement("div");
var Node = document.createElement("testing");
Node.appendChild( document.createElement("testingOne") );
var a = document.createAttribute("my_attrib");
node.setAttributeNode(a);
Node.appendChild( document.createElement("TestingTwo") );
Node.appendChild( document.createElement("TestingThree") );
XML.appendChild(Node);
alert(XML.innerHTML);
如何在Firefox附加组件中使用JavaScript创建XML,就像上面的示例一样?
答案 0 :(得分:1)
您希望在Firefox附加组件中使用JavaScript创建XML DOM树。在Firefox附加组件中这样做比在网页中运行的表单JavaScript更复杂。原因是无法保证window
和document
变量的设置。即使它们被设定,它们也可能不符合您的预期。 Firefox附加组件处理多个窗口和多个文档。因此,如果您使用window
和document
变量,则应始终确保将它们设置为您希望的变量。
在这个例子中,我们只找到最近使用的Firefox窗口的主要<window>
元素以及与当前显示的选项卡关联的<document>
元素。
以下代码将生成您想要的XML:
function createDesiredXMLElements() {
//To create elements, we need a <document>. To find a <document> we need a <window>.
//This gets the currently active Firefox XUL window.
// Add/remove a "/" to comment/un-comment the code appropriate for your add-on type.
//* Add-on SDK:
let activeWindow = require('sdk/window/utils').getMostRecentBrowserWindow();
//*/
/* Overlay and bootstrap (from almost any context/scope):
Components.utils.import("resource://gre/modules/Services.jsm");//Services
let activeWindow=Services.wm.getMostRecentWindow("navigator:browser");
//*/
//Get the HTML document for the currently displayed tab in the current Firefox window.
let contentDoc = activeWindow.content.document;
//To create XML elements, we need an XML document. We could do it without creating
// an XML document. But, then we would need to use createElementNS() to specify
// the XML namespace for each element. This way, they inherit the xmlDoc's namespace.
let xmlNS = "http://www.w3.org/XML/1998/namespace";
let xmlDoc = contentDoc.implementation.createDocument(xmlNS,"document");
//Create the XML elements/nodes/attribute and add text.
let testing = xmlDoc.createElement("testing");
let testingOne = xmlDoc.createElement("testingOne");
testingOne.setAttribute("attr","my_attrib");
let testingTwo = xmlDoc.createElement("TestingTwo");
testingTwo.textContent = "abc";
let testingThree = xmlDoc.createElement("TestingThree");
testingThree.textContent = "bbc";
//Place the elements as children of each appropriate node.
testing.appendChild(testingOne);
testingOne.appendChild(testingTwo);
testingOne.appendChild(testingThree);
//Show the alert. Note that the alert function is a method of a <window>:
activeWindow.alert(testing.outerHTML);
}
答案 1 :(得分:0)