dousou3027 2016-03-05 09:58
浏览 113
已采纳

如何通过PHP(domx)中包含冒号的属性名称选择xml元素?

Similar to the question here, I am trying to select xml elements by their attribute name, which contains a colon.

I am trying to do this with PHP, and my final goal is, to replace the content of these elements.

My code does not return any result:

$xml = '<?xml version="1.0" encoding="UTF-8" ?>
<a>
<aff xml:id="af1" value="a">
    <uAff>
        Hello
    </uAff>
</aff>
<aff xml:id="corr1">
    <uAff>
        Hello1
    </uAff>
</aff>
</a>';

$dom = new DOMDocument;
$dom->loadHTML($xml);
$xpath = new DOMXPath($dom);

$xelems = $xpath->query("/a/aff/@*[name()='xml:id']");
print_r($xelems);

foreach ($xelems as $node) {
    $node->nodeValue = 'New attribute value'; // changes the value of the xml:id attribute.';
   $node->parentNode->nodeValue = 'This does work!'; // changes the value of the element
}
echo htmlentities($dom->saveHTML());

How can this work with PHP?

  • 写回答

1条回答 默认 最新

  • dongzouche9108 2016-03-05 10:04
    关注

    The input is XML, so use loadXML instead of loadHTML.

    * selects elements. @* selects attributes.

    @*[name()='xml:id']
    

    You might also need to start the expression by // to make it search everywhere, not just under the root node.

    But then, much simpler expression might be used:

    //@xml:id
    

    or, with the full path

    /a/aff/@xml:id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分