问题描述
以这个 XML 为例:
Take this XML example:
<root>
<grandParent GPid="1" hidden="false">
<parent Pid="1" hidden="false">
<child Cid="1" hidden="false"/>
<child Cid="2" hidden="true"/>
</parent>
<parent Pid="2" hidden="false">
<child Cid="3" hidden="false"/>
<child Cid="4" hidden="false"/>
</parent>
</grandParent>
<grandParent GPid="2" hidden="false">
<parent Pid="3" hidden="false">
<child Cid="5" hidden="true"/>
</parent>
<parent Pid="4" hidden="true">
<child Cid="6" hidden="false"/>
</parent>
</grandParent>
<grandParent GPid="3" hidden="true">
<parent Pid="5" hidden="false">
<child Cid="7" hidden="false"/>
</parent>
</grandParent>
</root>
我需要某种过滤器来获取副本,其中所有标记为隐藏"的节点都被删除,如下所示:
I need some sort of filter to get a copy of this where all the nodes marked "hidden" are removed like so:
<root>
<grandParent GPid="1" hidden="false">
<parent Pid="1" hidden="false">
<child Cid="1" hidden="false"/>
</parent>
<parent Pid="2" hidden="false">
<child Cid="3" hidden="false"/>
<child Cid="4" hidden="false"/>
</parent>
</grandParent>
<grandParent GPid="2" hidden="false">
<parent Pid="3" hidden="false"/>
</grandParent>
</root>
我尝试使用这样的东西
var newXML:XML = XML(root.(grandParent.@hidden != "true").(grandParent.parent.@hidden != "true").(grandParent.parent.child.@hidden !=true);
但这实际上只是给了我原始的 XML(因为我要求满足这些条件的根,所以我得到了根).我明白为什么我的方法不起作用,但我不知道从哪里开始.
But that really just gives me back the original XML (since I'm asking for the root where those conditions are met I get the root). I understand why my approach doesn't work, but I don't know where to go from here.
推荐答案
假设您的 XML 位于变量 myXML 中,您可以使用这样的递归函数.这样做,您不会被绑定到元素的名称(即,grandParent、父、子)并且您不会受到级别数量的限制(即,您可以添加 ;
节点到每个 节点.)
You could use a recursive function like this assuming your XML is in a variable myXML. Doing it this way, you would not be tied to the name of your elements (ie. grandParent, parent, child) and you would not be restricted in the number of levels (ie. you could add a <pet>
node to each <child>
node.)
public function removeElements( avXml:XML, avAttributeName:String, avCondition:String) {
var lvAttributeValue:String;
var lvXml:XML;
var lvXmlList:XMLList = new XMLList();
for each( lvXml in avXml.children() ) {
lvAttributeValue = lvXml.attribute( avAttributeName );
if( lvAttributeValue == avCondition )
lvXmlList += lvXml;
avXml.setChildren( lvXmlList );
}
for each( var lvXmlChild:XML in avXml.children() ) {
removeElements(lvXmlChild,avAttributeName,avCondition);
}
}
removeElements(myXML, "hidden", "false");
trace(myXML.toXMLString());
<root hidden="false">
<grandParent GPid="1" hidden="false">
<parent Pid="1" hidden="false">
<child Cid="1" hidden="false"/>
</parent>
<parent Pid="2" hidden="false">
<child Cid="3" hidden="false"/>
<child Cid="4" hidden="false"/>
</parent>
</grandParent>
<grandParent GPid="2" hidden="false">
<parent Pid="3" hidden="false"/>
</grandParent>
</root>
这篇关于如何过滤掉 XML 的特定节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!