如何使用DOMXPath从php中的xml文件获取XML Element Attribute的值

here is simple XML File and i need to get the value of unitCode and i am using DOMXPath object to get the values.

<cbc:ConsumerUnitQuantity unitCode="BX">
    80.000
</cbc:ConsumerUnitQuantity>

i have tried

$unitCode = $xpath->query('//cbc:ConsumerUnitQuantity [@unitCode=""]')->item(0);
douzuo0002
douzuo0002 您可以使用cbc命名空间定义粘贴更完整的XML示例吗?
接近 7 年之前 回复

1个回答

You're missing the namespace. You XML elements have a namespace prefix, but you did not register one on the Xpath object. Check you document for a xmlns:cbc attribute.

$xml = <<<'XML'
<cbc:ConsumerUnitQuantity xmlns:cbc="your-namespace" unitCode="BX">
    80.000
</cbc:ConsumerUnitQuantity>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);

$xpath = new DOMXpath($dom);
$xpath->registerNamespace('ns-cbc', 'your-namespace');

var_dump(
  $xpath->evaluate('string(//ns-cbc:ConsumerUnitQuantity)', NULL, FALSE)
);

Unlike DOMXpath::query(), DOMXpath::evaluate() can return scalar values directly.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐