I am generating an XML File on the fly and want to remove certain childs by their attribute name.
我正在动态生成XML文件,并希望通过其属性名称删除某些子项。
For example: Data.xml
例如:Data.xml
<root>
<item name="item-1">
<sub1>some text</sub1>
<sub2>etc.</sub2>
</item>
<item name="item-2">
<sub1>some different text</sub1>
<sub2>etc.</sub2>
</item>
</root>
Now I am trying to remove an element by the attribute name. (i.e. "item-1")
现在我试图通过属性名称删除元素。 (即“第1项”)
That's how my XML Doc and my elements are set:
这就是我的XML Doc和我的元素的设置方式:
$doc = new DOMDocument('1.0', 'utf-8');
$root = $doc->createElement("root");
$doc->appendChild($root);
// Foreach... {
$item = $doc->createElement("item");
$item->setAttributeNode(new DOMAttr('name', 'item-'.$i));
$root->appendChild($item);
}
$doc->save("Data.xml")
I'd love to have something like: $doc->removeElementByAttributeValue("item-1"), but I can't find the trick :-(
我喜欢这样的东西:$ doc-> removeElementByAttributeValue(“item-1”),但我找不到诀窍:-(
1 个解决方案
#1
1
Use xpath to find the node:
使用xpath查找节点:
//item[@name='item-1']
which'll return the exact matching node, which you can then pass into the removeChild call
它将返回完全匹配的节点,然后您可以将其传递给removeChild调用
#1
1
Use xpath to find the node:
使用xpath查找节点:
//item[@name='item-1']
which'll return the exact matching node, which you can then pass into the removeChild call
它将返回完全匹配的节点,然后您可以将其传递给removeChild调用