草庐IT

php - 如何用php递归更新xml属性值?

coder 2024-07-05 原文

我正在编写一个函数来将给定 xml 文件的所有属性值重置为空字符串。有人可以帮我修复此功能以执行请求的任务吗?谢谢!

// reset all attribute values to NULL or ""
function resetAttributes($xml) {
    foreach($xml->children() as $child) {
        foreach($child->attributes() as $attr) {
            $attr = "";
        }
        resetAttributes($child);

    }
    return $xml;
}

$xml = simplexml_load_file($xmlFile);
resetAttributes($xml);
$xml->asXML($xmlFile);

//使用 Michael Berkowski 的解决方案进行修订!!内在 child 的属性保持不变。也许这是因为我的 PHP 版本?有关详细信息,请参阅底部的屏幕截图。

<?php
header('Content-type: text/plain');
$xmlString = <<<XMLSTR
<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description attr='12345'>An in-depth look at creating applications 
      with XML.</description>
      <sub attr='99'>
        <subsub attr1='asdb'/>
        <subsub attr1='asdb' attr2='xss'/>
      </sub>
   </book>
   <book id="bk102">
      <author  attr='54321' attr2='99999'>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price price='88888'>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
</catalog>
XMLSTR;

$xml = new RecursiveIteratorIterator(new SimpleXMLIterator($xmlString), RecursiveIteratorIterator::SELF_FIRST);
// Then just loop over it. The recursion will be automatic
foreach ($xml as $node) {
  foreach ($node->attributes() as $attr => $value) {
    // Set the attribute to an empty string the same way as in 
    // your recursive function...
    echo (string)$attr;
    $node->attributes()->$attr = '';
  }
}
// That's all, write out the XML.
echo '<pre>' . $xml->asXML() . '</pre>';
  1. http://img42.com/l9tSg
  2. http://img42.com/9b18L

最佳答案

你肯定在正确的轨道上,你的递归将正常工作,但在迭代属性时你应该使用 $attr => $valueforeach()并使用动态属性名称 $child->attributes()->$attr 按名称专门设置属性.这可能不是使用 SimpleXMLElement 执行此操作的唯一方法,但它很简单并且有效。

function resetAttributes($xml) {
    foreach($xml->children() as $child) {
        foreach($child->attributes() as $attr => $value) {
            // Call attributes() and identify the attribute by name
            // which you get from $attr in the iteration
            $child->attributes()->$attr = "";
        }
        // Recurse as you are doing...
        resetAttributes($child);
    }
    return $xml;
}

$xml = simplexml_load_file($xmlFile);
resetAttributes($xml);
$xml->asXML($xmlFile);

但是我们可以使用 PHP 的 SPL 迭代器做得更好...

理想情况下,您可以这样做 using a RecursiveIteratorIterator , 因为 SimpleXMLIterator 实现 RecursiveIterator界面。

// The SimpleXMLIterator constructor wants a string...
$xmlString = file_get_contents($xmlFile);
// Instantiate a new RecursiveIteratorIterator for SimpleXML
$xml = new RecursiveIteratorIterator(new SimpleXMLIterator($xmlString), RecursiveIteratorIterator::SELF_FIRST);
// Then just loop over it. The recursion will be automatic
foreach ($xml as $node) {
  foreach ($node->attributes() as $attr => $value) {
    // Set the attribute to an empty string the same way as in 
    // your recursive function...
    $node->attributes()->$attr = '';
  }
}
// That's all, write out the XML.
$xml->asXML($xmlFile);

关于php - 如何用php递归更新xml属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21869661/

有关php - 如何用php递归更新xml属性值?的更多相关文章

  1. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  2. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  3. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  4. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  5. ruby - 多个属性的 update_column 方法 - 2

    我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2

  6. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

  7. ruby - Nokogiri 剥离所有属性 - 2

    我有这个html标记:我想得到这个:我如何使用Nokogiri做到这一点? 最佳答案 require'nokogiri'doc=Nokogiri::HTML('')您可以通过xpath删除所有属性:doc.xpath('//@*').remove或者,如果您需要做一些更复杂的事情,有时使用以下方法遍历所有元素会更容易:doc.traversedo|node|node.keys.eachdo|attribute|node.deleteattributeendend 关于ruby-Nokog

  8. ruby-on-rails - Rails 模型——非持久类成员或属性? - 2

    对于Rails模型,是否可以/建议让一个类的成员不持久保存到数据库中?我想将用户最后选择的类型存储在session变量中。由于我无法从我的模型中设置session变量,我想将值存储在一个“虚拟”类成员中,该成员只是将值传递回Controller。你能有这样的类(class)成员吗? 最佳答案 将非持久属性添加到Rails模型就像任何其他Ruby类一样:classUser扩展解释:在Ruby中,所有实例变量都是私有(private)的,不需要在赋值前定义。attr_accessor创建一个setter和getter方法:classUs

  9. ruby - Chef Ruby 遍历 .erb 模板文件中的属性 - 2

    所以这可能有点令人困惑,但请耐心等待。简而言之,我想遍历具有特定键值的所有属性,然后如果值不为空,则将它们插入到模板中。这是我的代码:属性:#===DefaultfileConfigurations#default['elasticsearch']['default']['ES_USER']=''default['elasticsearch']['default']['ES_GROUP']=''default['elasticsearch']['default']['ES_HEAP_SIZE']=''default['elasticsearch']['default']['MAX_OP

  10. ruby - 获取数组中的值并最小化某个类属性的最优雅的方法是什么? - 2

    假设我有以下类(class):classPersondefinitialize(name,age)@name=name@age=ageenddefget_agereturn@ageendend我有一组Person对象。是否有一种简洁的、类似于Ruby的方法来获取最小(或最大)年龄的人?如何根据它对它们进行排序? 最佳答案 这样做会:people_array.min_by(&:get_age)people_array.max_by(&:get_age)people_array.sort_by(&:get_age)

随机推荐