douzhuo1853 2013-10-04 13:10
浏览 72
已采纳

使用DOMDocument修改XML文档正在对XML进行不必要的更改

I'm attempting to modify an xml file with DOMDocument. What I have is working, but it's adding more modifications to the xml file than I asked for.

Code:

$sDB = $this->oDB->getDBName();
$file = 'test.xml';

// Load XML
$dom = new DOMDocument;
$dom->preserveWhiteSpace = true;
$dom->formatOutput = false;
$dom->validateOnParse = false;
$dom->load($file);

// Find TEST Node
$nodes = $dom->getElementsByTagName('parameter');
foreach($nodes as $node)
{
    if($node->getAttribute('name') == 'TEST')
    {
        $sBDC = $node->nodeValue;
        $aBDC = explode(',',$sBDC);
        if(!in_array($sDB,$aBDC))
            array_push($aBDC,$sDB);
        $sBDC = implode(',',$aBDC);
        $node->nodeValue = $sBDC;
        $dom->save($file);
        break;
    }
}

Some of the XML:

<parameter name="Integration" username="testuser" password="testpassword">/parameter>
<parameter name="API">accept.php</parameter>
<parameter name="TRANSFER" username="admin" password="letmein" />
<parameter name="TEST">dbname</parameter>

The problem:

It's adding <?xml version="1.0"?> to the beginning of the XML file and it's modifying some of the <parameter> elements by making any unnecessary ending tags inline if there is no value. For example <parameter name="email"></parameter> would become <parameter name="email" />. It's also removing some other unnecessary white space within the elements.

While my gut instinct is telling me these changes won't hurt anything, I'd feel much more comfortable with this if the only changes taking place were the intended ones. Unfortunately, it wouldn't surprise me if there was some code buried somewhere that's actually looking for these unnecessary white-spaces.

  • 写回答

1条回答 默认 最新

  • doudou_3636 2013-10-04 13:30
    关注

    Well, a valid XML file will have the XML definition. Also, you can keep it from using the self closing tags by using LIBXML_NOEMPTYTAG flag in the save().

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

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应