douzhuo3233 2016-06-24 08:50
浏览 38
已采纳

解析symfony xml配置

I have a symfony xml-config and need to parse it.

<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

<parameters>
    <parameter key="abcxyz" type="collection">
        <parameter key="abc" type="collection">
            <parameter key="a" type="string">a</parameter>
            <parameter key="b" type="string">b</parameter>
            <parameter key="c" type="constant">\My\Bundle\Type::TYPE_ABC</parameter>
        </parameter>
        <parameter key="xyz" type="collection">
            <parameter key="x" type="string">x</parameter>
            <parameter key="y" type="string">y</parameter>
            <parameter key="z" type="constant">\My\Bundle\Type::TYPE_XYZ</parameter>
        </parameter>
    </parameter>
</parameters>
</container>

and I need to get the values "abc" and "xyz". I tried to get it with

$simpleXml = simplexml_load_string(file_get_contents(__DIR__ . '/myConfig.xml');
var_dump($simpleXml->xpath('//parameters/parameter/parameter/@key'));

but the result is empty...

  • 写回答

1条回答 默认 最新

  • duanmei1894 2016-06-24 09:08
    关注

    Add a namespace to the xml element and change the xpath query like this:

    $simpleXml->registerXPathNamespace("s", "http://symfony.com/schema/dic/services");
    $s=$simpleXml->xpath("//s:parameters/s:parameter/s:parameter/@key");
    var_dump($s);
    

    This will give the result that you want:

    array (size=2)
      0 => 
        object(SimpleXMLElement)[6]
          public '@attributes' => 
            array (size=1)
              'key' => string 'abc' (length=3)
      1 => 
        object(SimpleXMLElement)[7]
          public '@attributes' => 
            array (size=1)
              'key' => string 'xyz' (length=3)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向