如何在XML中创建和设置属性的值? [英] How to create and set values for attribute in XML?

查看:148
本文介绍了如何在XML中创建和设置属性的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在XML中创建和设置属性的值?我需要设置ateam id =101?
这样我列出了我的代码。通过使用createAttribute我创建,但我不知道如何设置该属性的值。

How to create and set values for attribute in XML ? I need to set ateam id="101" ? With this I listed my code. By using createAttribute i created but i dont know how to set value for that attribute..

/* create XML Content */
 $domtree = new DOMDocument('1.0', 'UTF-8');
 $xmlRoot = $domtree->createElement("xml");
 $xmlRoot = $domtree->appendChild($xmlRoot);
 $currentTrack = $domtree->createElement("messsage");
 $currentTrack = $xmlRoot->appendChild($currentTrack);
 $currentTrack->appendChild($domtree->createElement('category','Scores'));
 $Game = $currentTrack->appendChild($domtree->createElement('Game',''));
 $Game->appendChild($v = $domtree->createElement('ateam','India'));
 $Game->appendChild($domtree->createElement('score',30));
 $v->appendChild($domtree->createAttribute('id'));
  echo $domtree->saveXML();

OUTPUT

<?xml version="1.0" encoding="UTF-8"?>
<xml>
    <messsage>
        <category>Scores</category>
        <Game>
            <ateam id="">India</ateam>
            <score>30</score>
        </Game>
    </messsage>
</xml>

预期输出

 <?xml version="1.0" encoding="UTF-8"?>
    <xml>
        <messsage>
            <category>Scores</category>
            <Game>
                <ateam id="101">India</ateam>
                <score>30</score>
            </Game>
        </messsage>
    </xml>


推荐答案

最简单的方法是使用 setAttribute

The easiest way is using setAttribute:

$v->setAttribute('id', 101);

这篇关于如何在XML中创建和设置属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆