代码之家  ›  专栏  ›  技术社区  ›  Kamil Szot

如何设置simplexmlement的文本值而不使用其父级?

  •  20
  • Kamil Szot  · 技术社区  · 14 年前

    我想设置xpath()找到的某个节点的文本

    <?php
    
    $args = new SimpleXmlElement(
    <<<XML
    <a>
      <b>
        <c>text</c>
        <c>stuff</c>
      </b>
      <d>
        <c>code</c>
      </d>
    </a>
    XML
    );
    
    // I want to set text of some node found by xpath 
    // Let's take (//c) for example
    
    // convoluted and I can't be sure I'm setting right node
    $firstC = reset($args->xpath("//c[1]/parent::*")); 
    $firstC->c[0] = "test 1";
    
    // like here: Found node is not actually third in its parent.
    $firstC = reset($args->xpath("(//c)[3]/parent::*")); 
    $firstC->c[2] = "test 2";
    
    // following won't work for obvious reasons, 
    // some setText() method would be perfect but I can't find nothing similar, 
    $firstC = reset($args->xpath("//c[1]"));
    $firstC = "test"; 
    
    // maybe there's some hack for it?
    $firstC = reset($args->xpath("//c[1]"));
    $firstC->{"."} = "test"; // nope, just adds child named .
    $firstC->{""} = "test"; // still not right, 'Cannot write or create unnamed element'
    $firstC["."] = "test"; // still no luck, adds attribute named .
    $firstC[""] = "test"; // still no luck, 'Cannot write or create unnamed attribute'
    $firstC->addChild('','test'); // grr, 'SimpleXMLElement::addChild(): Element name is required'
    $firstC->addChild('.','test'); // just adds another child with name .
    
    echo $args->asXML();
    
    // it outputs:
    // 
    // PHP Warning:  main(): Cannot add element c number 2 when only 1 such elements exist 
    // PHP Warning:  main(): Cannot write or create unnamed element 
    // PHP Warning:  main(): Cannot write or create unnamed attribute 
    // PHP Warning:  SimpleXMLElement::addChild(): Element name is required 
    // <?xml version="1.0"? >
    // <a>
    //  <b>
    //   <c .="test">test 1<.>test</.><.>test</.></c>
    //   <c>stuff</c>
    //  </b>
    //  <d>
    //   <c>code</c>
    //  <c>test 2</c></d>
    // </a>
    
    2 回复  |  直到 13 年前
        1
  •  38
  •   Community Ramakrishna.p    7 年前

    你可以做一个 SimpleXMLElement自引用 :

    $firstC->{0} = "Victory!!"; // hackity, hack, hack!
    //  -or-
    $firstC[0]   = "Victory!!";
    

    var_dump((array) reset($xml->xpath("(//c)[3]")))
    

    这也适用于 unset 中概述的操作 an answer to :

        2
  •  8
  •   Josh Davis    14 年前

    真正的答案是:你不能。

    DOM 例如。

    dom_import_simplexml($node)->nodeValue = 'foo';