douxin2003 2013-11-19 11:14
浏览 34
已采纳

如何在元素标记之间创建包含文本的元素

I have made this function:

protected function _addElement($xmlDocument, $elementName, $parentElement){
    $element = $xmlDocument->createElement($elementName);
    return $parentElement->appendChild($element);
}

and I call it, i.e., in this way:

$Street = $this->_addElement($xmlDocument, 'Steet', $xmlDocument);
$House = $this->_addElement($xmlDocument, 'House', $Street);

and in the created XML document I will have it looking like that:

<Street>
   <House //maybe some attributes />
</Street>

So, the createElement($elementName) function is from the DOM API, that I call upon the DOM object $xmlDocument and it will create a closed node. What I need is to use a function that, with which I will get to the following result:

<Street>
   <Yard> the dog pooped all over the backyard </Yard>
</Steet>

I looked in the DOM API for something involving text, etc. I stumbled upon createTextNode($content) but that is something kinda' different, or maybe I just didn't understand correctly, when I read the documentiation.

  • 写回答

1条回答 默认 最新

  • duanhaodi4809 2013-11-19 11:26
    关注

    Since you're using DOMDocument::createElement, you'll notice from the method definition that it has a 2nd non-mandatory argument:

    public DOMElement DOMDocument::createElement ( string $name [, string $value ] )
    

    Just update your code to:

    protected function _addElement($xmlDocument, $elementName, $elementValue, $parentElement) {
        $element = $xmlDocument->createElement($elementName, $elementValue);
        return $parentElement->appendChild($element);
    }
    

    and:

    $Street = $this->_addElement($xmlDocument, 'Steet', 'My street', $xmlDocument);
    $House  = $this->_addElement($xmlDocument, 'House', 'My house', $Street);
    

    That way you'll be able to add elements with the values you want. Remember that if you want to add attributes to the newly created elements you'll have to use the DOMDocument::createAttribute function on the $element variable before calling appendChild.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 matlab解优化问题代码
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
  • ¥15 学不会递归,理解不了汉诺塔参数变化
  • ¥15 基于图神经网络的COVID-19药物筛选研究
  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline