【问题标题】:asXML destroy xml file?asXML 销毁 xml 文件?
【发布时间】:2011-12-13 14:59:39
【问题描述】:

您好,我对 php 中的 asXML 函数有疑问。假设我有一个名为 xml_file 并具有以下内容的 xml 文件。

<employees>
  <employee>
    <name>Mark</name>
    <age>27</age>
    <salary></salary>
  </employee>
  <employee>
    <name>Jack</name>
    <age>25</age>
    <salary>$4000</salary>
  </employee>
</employees>

我编写了这段代码来更改我的 xml 文件中的变量。

$xml = new SimpleXMLElement(file_get_contents($xml_file));
$xml->employee[1]->name = 'David';
$xml->asXML($xml_file) or die ("asXML failed.\n");

我的问题是,由于第一个工资标签是空的,asXML 函数会破坏这个标签,它会像那样输出

<employees>
  <employee>
    <name>Mark</name>
    <age>27</age>
    <salary/>
  </employee>
  <employee>
    <name>David</name>
    <age>25</age>
    <salary>$4000</salary>
  </employee>
</employees>

如何防止这种情况发生?感谢您提供任何适当的解决方案...

【问题讨论】:

    标签: php xml simplexml


    【解决方案1】:

    在 XML 中:-

    <salary></salary> = <salary/>  <-- both are empty tag
    

    【讨论】:

    • 稍微扩展一下:两者是完全等价的。如果您的软件接受&lt;salary&gt;&lt;/salary&gt; 而不是&lt;salary/&gt;那么它已损坏,您不应该使用它来解析 XML
    猜你喜欢
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 2011-11-08
    • 2015-06-26
    • 2015-12-07
    • 1970-01-01
    • 2012-10-21
    • 2015-10-19
    相关资源
    最近更新 更多