这取决于您所说的“价值”。如果你有类似的东西
<spec3 />Value</spec3>
那么 readInnerXML 应该会给你你的价值。
如果您的值在属性中,
<spec1 foo="my attribute" />
您需要使用 XMLReader 对象的 getAttribute 方法,或者明确告诉读者开始解析属性。请参阅下面的代码示例,了解实现此目的的几种方法。
最后,如果节点包含更多嵌套的 XML,
<spec2><foo><baz thing="la de da">Value</baz></foo></spec2>
在那一刻,读者没有直接的方法来理解其中的价值/元素。您需要执行以下操作之一
- 更改您的阅读器解析代码以挂钩那些深度的元素
- 从 readInnerXML 中获取 XML 块并使用第二个 XMLReader 实例开始解析它,
- 从 readInnerXML 中获取 XML 块并开始使用另一个 XML 解析库对其进行解析。
这是一些用于解析属性的示例代码
$reader = new XMLReader();
$reader->xml(trim('
<root>
<thing>
<specs>
<spec1 foo="my attribute">Value</spec1>
<spec3>
My Text
</spec3>
<spec2 foo="foo again" bar="another attribute" baz="yet another attribute" />
</specs>
<details />
<more_info>
<info1 />
<info2 />
</more_info>
</thing>
</root>
'));
$last_node_at_depth = array();
$already_processed = array();
while($reader->read()){
$last_node_at_depth[$reader->depth] = $reader->localName;
if(
$reader->depth > 0 &&
$reader->localName != '#text' &&
$last_node_at_depth[($reader->depth-1)] == 'specs' &&
!in_array ($reader->localName,$already_processed)
){
echo "\n".'Processing ' . $reader->localName . "\n";
$already_processed[] = $reader->localName;
echo '--------------------------------------------------'."\n";
echo 'The Value for the inner node ';
echo ' is [';
echo trim($reader->readInnerXML());
echo ']'."\n";
if($reader->attributeCount > 0){
echo 'This node has attributes, lets process them' . "\n";
//grab attribute by name
echo ' Value of attribute foo: ' . $reader->getAttribute('foo') . "\n";
//or use the reader to itterate through all the attributes
$length = $reader->attributeCount;
for($i=0;$i<$length;$i++){
//now the reader is pointing at attributes instead of nodes
$reader->moveToAttributeNo($i);
echo ' Value of attribute ' . $reader->localName;
echo ': ';
echo $reader->value;
echo "\n";
}
}
//echo $reader->localName . "\n";
}
}