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().

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

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写