根据项目代码

时间:2016-03-03 10:29:34

标签: javascript xml internet-explorer

完全是javascript和xml的新手,我想从以下xml文档的项目中删除一行:

<TEXTS>
 <Text Name="NewProject">NEW PROJECT</Text>
 <Text Name="Continue">CONTINUE</Text>
 <Text Name="RecentProjects">Recently used Projects:</Text>
</TEXTS>
 <LIST>
<Project ID="Visible" Name="Example1" />
<Project ID="Visible" Name="adgjhh" />
<Project ID="Visible" Name="dthdth" />
<Project ID="Visible" Name="rssrhsrh" />
<Project ID="Visible" Name="aaaef" />
<Project ID="Visible" Name="aeeaaet" />
<Project ID="Visible" Name="aeteta" />
<Project ID="Visible" Name="aetetaetaetaetaeta" />
<Project ID="Visible" Name="agdadg" />
<Project ID="Visible" Name="dga" />
<Project ID="Visible" Name="ghfj" />
<Project ID="Visible" Name="hsrh" />
<Project ID="Visible" Name="hteah" />
<Project ID="Visible" Name="jrrjyrjy" />
<Project ID="Visible" Name="jyrryjry" />
<Project ID="Visible" Name="wtwet" />
<Project ID="Visible" Name="yrryry" />
<Project ID="Visible" Name="yrtry" />
</LIST>

这是我在JS中的尝试:

 var fname="listOfProjects.xml";
        var xmldoc;

        var activeProjects;
        var inactiveProjects;

        var clickable;
        var greyed;

        var nodes;

        xmldoc= new ActiveXObject("Msxml2.DOMDocument");
        xmldoc.load(fname);
        activeProjects = xmldoc.selectNodes("/STARTPAGE/LIST/Project[@ID='Visible']");
        clickable = "<LIST>";

        // Try and delete a random project for now
        var y = xmldoc.getElementsByTagName("Project")[5];
        y.parentNode.removeChild(y);
        //xmldoc.documentElement.removeChild(y);

说我要删除项目“Example1”。第一步是能够根据索引删除它。我的第二个目标是能够根据文本删除它,这意味着我想搜索所有项目,并删除所有项目中的“Example1”。

1 个答案:

答案 0 :(得分:1)

要选择节点,您可以使用XPath,例如

xmldoc.setProperty('SelectionLanguage', 'XPath');
var el = xmldoc.selectSingleNode('//Project[@name = "Example1"]');

从DOM中删除选定的节点

if (el != null) {
  el.parentNode.removeChild(el);
}

将DOM中所做的更改保存到文件中使用save方法,即

xmldoc.save("result.xml");