一个构建XML对象的js库

初学javascript,学习中用到在IE中建立XML对象,于是写了一个简单的“库”。因为水平所限,肯定会有不恰当的地方,欢迎指正。

如果大家有知道现存的更好的东西,非常希望大家能将它推荐给我。

代码:

function XmlObject() {
    var oXml = new ActiveXObject("Microsoft.XMLDOM");
    this.getXmlObj = function() {
        return oXml;
    }
    this.InitXmlObj = function() {
        oXml = new ActiveXObject("Microsoft.XMLDOM"); //对象
    }
    this.isTop = function(oNode) {
        if (oNode === oXml) return true;
        return false;
    }
    this.AddTextNode = function(oParent, sKey, sValue) {
        if (this.isTop(oParent) == true) {
            //为顶级对象添加的节点不能超过一个
            if (oXml.childNodes.length > 0) {
                //已经存在根节点,不继续添加
                return null;
            }
        }
        var oNewNode = oXml.createElement(sKey);
        var oTextNode = oXml.createTextNode(sValue);
        oParent.appendChild(oNewNode);
        oNewNode.appendChild(oTextNode);
        return oNewNode;
    }
    this.AddAttrNode = function(oParentNode, sNodeName, sAttr, sValue) {
        if (this.isTop(oParent) == true) {
            //为顶级对象添加的节点不能超过一个
            if (oXml.childNodes.length > 0) {
                //已经存在根节点,不继续添加
                return null;
            }
        }
        var oNewNode = oXml.createElement(sNodeName);
        oParentNode.appendChild(oNewNode);
        oNewNode.setAttribute(sAttr, sValue);
        return oNewNode;
    }
    this.AddAttrTextNode = function(oParentNode, sNodeName, sNodeText, sAttrName, sAttrValue) {
        if (this.isTop(oParentNode) == true) {
            //为顶级对象添加的节点不能超过一个
            if (oXml.childNodes.length > 0) {
                //已经存在根节点,不继续添加
                return null;
            }
        }
        var oNewNode = oXml.createElement(sNodeName);
        var oTextNode = oXml.createTextNode(sNodeText);
        oParentNode.appendChild(oNewNode);
        oNewNode.setAttribute(sAttrName, sAttrValue);
        oNewNode.appendChild(oTextNode);
        return oNewNode;
    }
    this.getXmlStr = function() {
        return oXml.xml;
    }
}

演示代码:

function onXml() {
    var oXmlOp = new XmlObject();
    var oTop = oXmlOp;
    var oTop = oXmlOp.AddAttrTextNode(oXmlOp.getXmlObj(), "UserInfo", "", "class", "dianxin1005");
    oXmlOp.AddAttrTextNode(oTop, "Subject", "Chinese", "Score", "98");
    oXmlOp.AddAttrTextNode(oTop, "Subject", "Math", "Score", "77");
    oXmlOp.AddAttrTextNode(oTop, "Subject", "English", "Score", "99");
    alert(oXmlOp.getXmlStr());
}

  

生成的XML是:

<UserInfo class="dianxin1005">
    <Subject Score="98">
        Chinese
    </Subject>
    <Subject Score="77">
        Math
    </Subject>
    <Subject Score="99">
        English
    </Subject>
</UserInfo>

  

原文地址:https://www.cnblogs.com/sunsoftresearch/p/3533452.html