我具有以下XML结构:
<?xml version="1.0" encoding="ISO-8859-1"?>
<articles>
<article id="1">
<title>Article title 001</title>
<short>Short text</short>
<long>Long text</long>
</article>
<article id="2">
<title>Article title 002</title>
<short>Short text</short>
<long>Long text</long>
</article>
</articles>
我只想选择
<title>
和<short>
。当前使用它来显示所有内容:
$queryResult = $xpathvar->query('//articles/article'); // works fine grabs all articles
foreach($queryResult as $result){
echo $result->textContent;
}
预期的输出将是:
文章标题001
短文字
任何帮助将不胜感激。
工作解决方案!
if ($artId == "") {
$queryResult = $xpathvar->query('//articles/article/*'); // grab all children
foreach($queryResult as $result){
if($result->nodeName === 'title' || $result->nodeName === 'short') {
echo $result->textContent;
}
}
}else{
$queryResult = $xpathvar->query(sprintf('//articles/article[@id="%s"]/*', $artId)); // Show requested article
foreach($queryResult as $result){
if($result->nodeName === 'title' || $result->nodeName === 'long') {
echo $result->textContent;
}
}
}
最佳答案
您可以使用
/articles/article/*[name()="title" or name()="short"]
这只会返回元素名称为“ title”或“ short”的任何“ article / article”的子代。
另一种方法是,将XPath更改为
/articles/article/*
以获取文章的所有childNode,并在迭代$results
时检查DOMNode::nodeName
是“ title”还是“ short”,例如$queryResult = $xpathvar->query('/articles/article/*'); // grab all children
foreach($queryResult as $result){
if($result->nodeName === 'title' || $result->nodeName === 'short') {
echo $result->textContent;
}
}
如果您不想更改XPath,则必须迭代文章的
childNodes
,例如$queryResult = $xpathvar->query('/articles/article');
foreach($queryResult as $result) {
foreach($result->childNodes as $child) {
if($child->nodeName === 'title' || $child->nodeName === 'short') {
echo $child->textContent;
}
}
关于php - 选择一些而非全部子节点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3976853/