如何从XML中删除某些特定标记

时间:2017-01-27 05:07:11

标签: javascript html arrays xml

我有一个类似下面的XML,我想在Players

时删除Flg = 1标记
<sports>
    <cricket Team = England>
        <Players Name = "EAA" Flg = "0"></Players>
        <Players Name = "EAB" Flg = "1"></Players>
    </cricket>
    <cricket Team = India>
        <Players Name = "IAA" Flg = "0"></Players>
        <Players Name = "IAB" Flg = "1"></Players>
    </cricket>
    <cricket Team = Aus>
        <Players Name = "AAA" Flg = "0"></Players>
        <Players Name = "AAB" Flg = "1"></Players>
    </cricket>
</sports>

所以我在这里尝试的是

var Players = xml.getElementsByTagName('Players');
var arr = Array.prototype.slice.call( Players  )
for(var i=0; i<arr.length; i++)
{
    var FlgAtt = arr[i].getAttribute('Flg');
    if(Flg == "1" ){
        arr.splice(i,1)
    }
}

但是在最终的XML中,这些播放器标签仍然可用。我的最终输出应该是

<sports>
    <cricket Team = England>
        <Players Name = "EAA" Flg = "0"></Players>
    </cricket>
    <cricket Team = India>
        <Players Name = "IAA" Flg = "0"></Players>
    </cricket>
    <cricket Team = Aus>
        <Players Name = "AAA" Flg = "0"></Players>
    </cricket>
</sports>

有人可以告诉我我做错了什么以及如何解决这些问题?

2 个答案:

答案 0 :(得分:3)

假设document

Array.from(document.querySelectorAll('Players[Flg="1"]')).forEach(
  x => x.parentNode.remove(x)
);

JavaScript从文档中删除节点的方法是parent.remove(child)。正如评论所说,从数组中删除某些内容不会将其从文档中删除。

答案 1 :(得分:0)

在本地尝试此代码,它将删除节点,并最终需要在xml文件中编写XmlDoc。

xmlString = '<sports><cricket Team="England"><Players Name="EAA" Flg="0"></Players><Players Name="EAB" Flg="1"></Players></cricket><cricket Team="India"><Players Name="IAA" Flg="0"></Players><Players Name="IAB" Flg="1"></Players></cricket><cricket Team="Aus"><Players Name="AAA" Flg="0"></Players><Players Name="AAB" Flg="1"></Players></cricket></sports>'

var parser, xmlDoc;
parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlString, "text/xml");
var tag = xmlDoc.getElementsByTagName("cricket");
for (x in tag) {
  for (y in tag[x].childNodes) {
    node = tag[x].childNodes[y];
    for (attr in node.attributes) {
      if ((node.attributes[attr].nodeName == "Flg") && (node.attributes[attr].nodeValue == "1"))
        node.remove();
    }
  }
}
console.log(xmlDoc);

另一种方式:

xmlString = '<sports><cricket Team="England"><Players Name="EAA" Flg="0"></Players><Players Name="EAB" Flg="1"></Players></cricket><cricket Team="India"><Players Name="IAA" Flg="0"></Players><Players Name="IAB" Flg="1"></Players></cricket><cricket Team="Aus"><Players Name="AAA" Flg="0"></Players><Players Name="AAB" Flg="1"></Players></cricket></sports>'

var parser, xmlDoc;
parser = new DOMParser();
xmlDoc = parser.parseFromString(xmlString, "text/xml");

var tag = xmlDoc.querySelectorAll("Players[Flg='1']");
var f=Array.from(tag);
f.forEach(x=>x.remove());

console.log(xmlDoc);