【问题标题】:How to get each node's attribute via xpath如何通过xpath获取每个节点的属性
【发布时间】:2011-11-09 15:48:14
【问题描述】:

如何通过 xpath 获取每个节点的属性?

例如,

book.xml,

<?xml version="1.0" encoding="UTF-8" ?>
<records timestamp="1264777862">
<record></record>
<record></record>
<record timestamp="1264777000"></record>
<record></record>
</records>

php,

<?php

$doc = new DOMDocument;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

# get and output "<entry>" elements
$x = $doc -> getElementsByTagName('record');

# Count the total feed with xpath.
$total = $x->length;

# the query is relative to the records node
$query = 'string(/records/@timestamp)';

for ($i=0; $i<$total; $i++)
{
    $timestamp = $xpath->evaluate($query,$x->item($i));
    echo $timestamp ."<br/>";
}

?>

结果(它只循环第一个节点),

1264777862
1264777862
1264777862
1264777862

但我想得到,

1264777862
1264777000

我已经按照here的问答进行了修改。

或者也许有更好的方法?

编辑:

xml,

<?xml version="1.0" encoding="UTF-8" ?>
<records>
    <record timestamp="1264777862">A</record>
    <record>B</record>
    <record timestamp="1264777000">C</record>
    <record>D</record>
</records>

有了这个,

for ($i=0; $i<$total; $i++)
{
    $value = $x->item($i)->childNodes->item(0)->nodeValue;
    $timestamp = $xpath->evaluate($query,$x->item($i));
    echo $value.': '.$timestamp ."<br/>";
}

我得到了这个结果,

A: 1264777862
B: 1264777862
C: 1264777862
D: 1264777862

但这是我追求的结果,

A: 1264777862
B: 
C: 1264777862
D: 

编辑:

一个测试,

$nodes = $xpath->query('//records/record');

foreach($nodes as $node) {
    $value = $node->nodeValue;
    $timestamp = $node->getAttribute('timestamp');
    echo $value .': '."<br/>";
}

结果,

A: 
B: 
C: 
D: 

【问题讨论】:

  • 您的 XML 在records 上有一个属性,在record 上有一个属性。你想和哪个合作?
  • 对不起我的错误。请参阅我上面的编辑。谢谢。

标签: php xml xpath domdocument


【解决方案1】:

一种方法:

$nodes = $xpath->query('//records[@timestamp]');
foreach($nodes as $node) {
    $timestamp = $node->getAttribute('timestamp');
}

不过,您在示例中混合使用了 recordrecords,所以我不确定您实际使用的是哪个。


更新:此代码适用于我:

<?php

$xml = <<<EOL
<?xml version="1.0" encoding="UTF-8" ?>
<records>
    <record timestamp="1264777862">A</record>
    <record>B</record>
    <record timestamp="1264777000">C</record>
    <record>D</record>
</records>
EOL;

$x = new DOMDocument();
$x->loadXML($xml);

$xp = new DOMXpath($x);

$nodes = $xp->query('//records/record');
foreach($nodes as $node) {
   echo $node->nodeValue, ': ', $node->getAttribute('timestamp'), "\n";
}

和输出

A: 1264777862
B:
C: 1264777000
D:

【讨论】:

  • 对不起,我的错误。请参阅我上面的编辑。我收到getAttrribute 的错误消息,谢谢。
  • 哎呀。错字。应该是 getAttribute(一个 r)。
  • 抱歉,我刚刚意识到另一个问题,因为我需要在结果中提供更多信息。我猜我不能在你的回答中使用查询 u。你能看看我上面的编辑吗?谢谢。
  • 所以你想输出所有record节点,不管它们是否有时间戳属性?使用 //records 作为 xpath,然后使用 $node-&gt;nodeValue 来获取 a/b/c/d 的东西。
  • 之后如何使用getAttribute('timestamp')?请参阅我上面的编辑。谢谢。
猜你喜欢
  • 1970-01-01
  • 2011-06-17
  • 1970-01-01
  • 1970-01-01
  • 2022-10-06
  • 1970-01-01
  • 1970-01-01
  • 2016-05-21
  • 1970-01-01
相关资源
最近更新 更多