[英]PHP: How to change part of XML using DomElement
I am trying to make a function that changes part of an XML using XPath. 我正在尝试制作一个使用XPath更改XML部分的函数。 I used part of someone else post:
我使用了其他人的帖子:
/*********************************************************************
Function to replace part of an XML
**********************************************************************/
function replacePartofXML($element, $methodName, $methodValue, $xml, $newPartofXML)
{
$xpathstring = "//" . $element . "[@$methodName = \"$methodValue\"]";
$xml->xpath($xpathstring);
//$domToChange = dom_import_simplexml($xml->xpath($xpathstring));
$domToChange = dom_import_simplexml($xml);
$domReplace = dom_import_simplexml($newPartofXML);
$nodeImport = $domToChange->ownerDocument->importNode($domReplace, TRUE);
$domToChange->parentNode->replaceChild($nodeImport, $domToChange);
return($xml);
}
What I want to do is return the appended XML. 我想做的是返回附加的XML。 I can't use dom_import_simplexml($xml->node->node) as my XML has many repeating element (but they have different ID reason why I am trying to use xpath)
我不能使用dom_import_simplexml($ xml-> node-> node),因为我的XML有很多重复元素(但是它们具有不同的ID,因此我尝试使用xpath)
The commented line does not work either as xpath returns an array and dom_import_simplexml is cannot import arrays. 注释行不起作用,因为xpath返回一个数组,而dom_import_simplexml无法导入数组。
Thanks for you input 感谢您的输入
You can take the first element returned by xpath()
in case you believe the target element is unique (no-element-returned checking omitted) : 如果您认为目标元素是唯一的(可以省略无元素返回的检查),则可以采用
xpath()
返回的第一个元素:
$domToChange = dom_import_simplexml($xml->xpath($xpathstring)[0]);
or iterate through the return value of xpath()
and replace one by one. 或遍历
xpath()
的返回值并一一替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.