douneiben2240 2014-05-10 00:08
浏览 52

使用replaceChild php DOM替换TextNode

I have this XML file and I need to replace te value of qteStock using the php DOM,but I still can't get the concept.Can anyone help me please?

<?xml version="1.0" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="Marque.xsl" ?>
<Marques xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="Marques.xsd">    
<Marque>
   <codeMarque>00003</codeMarque>
   <nomMarque>Diesel</nomMarque>
   <paysOrigine>USA</paysOrigine>
   <qteStock>50</qteStock>
   <qteLimite>5</qteLimite>
</Marque>
</Marques>

This is the php code I've been trying to manipulate:

<?php
$marque=$_POST['nomMarque'];
$qte=$_POST['qte'];

$xmlstring = 'entities/Marques.xml';
$dom = new DOMDocument; 
$dom->load($xmlstring);

$xpath = new DOMXPath($dom);

$query = "//Marque[nomMarque='".$marque."']/qteStock";
$qteStock = $xpath->query($query);

$query = "//Marque[nomMarque='".$marque."']/qteLimite";
$qteLimite = $xpath->query($query);

$nouvelleQuantite = $qteStock->item(0)->nodeValue-$qte ;
$newQuantity = $dom->createTextNode($nouvelleQuantite);

$return = ($qteStock->replaceChild($newQuantity,$qteStock);
$dom->save('entities/Marques.xml');
?>
  • 写回答

1条回答 默认 最新

  • dongpao2871 2014-05-10 15:30
    关注

    You can set the nodeValue property of the element node - integers do not need escaping in XML. If you need to write text that could contain &, set the nodeValue to an empty string (deletes all child nodes) and insert a new text node.

    $changeValue = 5;
    
    $dom = new DOMDocument();
    $dom->loadXml($xml);
    $xpath = new DOMXpath($dom);
    
    $nodes = $xpath->evaluate('/Marques/Marque[1]/qteStock');
    // node found?
    if ($nodes->length > 0) {
      $stock = $nodes->item(0);
      $newValue = $stock->nodeValue - $changeValue;
      // just set the content (an int does not need any escaping)
      $stock->nodeValue = (int)$newValue;
    }
    
    echo $dom->saveXml();
    

    Demo: https://eval.in/149098

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog