2016-12-30 65 views
0

如何獲得每個節點FLOWER的所有屬性值ID?使用Xpath選擇屬性並列出基於NODE值的值

<Files> 
<data id="1"> 
    <Type>Flower</Type> 
</data> 
<data id="2"> 
    <Type>Flower</Type> 
</data> 
<data id="3"> 
    <Type>Flower</Type> 
</data> 
<data id="4"> 
    <Type>Flower</Type> 
</data> 
</Files> 

在MySQL的情況下它會像SELECT id from Files WHERE Type="Flower"

如何做這種情況下我的代碼的XPath?

並在選項框內使用SimpleXML列出它。

<select> 
<?php 
foreach ($type as $id) { 
echo '<option value="'.$id.'">'.$id.'</option>'; 
} 
?> 
</select> 

回答

1

要獲得所有@id屬性值嘗試

/Files/data[normalize-space(Type) = 'Flower']/@id 
+0

謝謝選擇作爲答案,因爲它比以前的答案更簡單!雖然兩者都很好。 –

1
'//data[(./Type/text()="Flower")]/@id' 
+0

Thanks Works!但我明智地得到了一個更簡單的Answered語法。 –

1

你的XML是無效的,封閉根元素不匹配,並且Type元素被封閉,type。 XML區分大小寫。

Xpath工作使用位置路徑和條件位置路徑是從當前上下文到元素的分層路徑。他們返回一個節點列表。該列表可以使用條件進行過濾。

SimpleXMLElement對象有一個方法xpath()在關聯節點的上下文中執行表達式。

$xml = <<<'XML' 
<Files> 
<data id="1"> 
    <type>Flower</type> 
</data> 
<data id="2"> 
    <type>Flower</type> 
</data> 
<data id="3"> 
    <type>Flower</type> 
</data> 
<data id="4"> 
    <type>Flower</type> 
</data> 
</Files> 
XML; 

$files = new SimpleXMLElement($xml); 

$target = new SimpleXMLElement('<select/>'); 
foreach ($files->xpath('data[type = "Flower"]') as $data) { 
echo '.'; 
    $option = $target->addChild('option', $data['id']); 
    $option['value'] = $data['id']; 
} 
echo $target->asXml(); 

你不應該創建你的XML文本。爲它使用XML Api。

DOM更加具體和強大。例如,您可以將創建的DOM序列化爲HTML。

$source = new DOMDocument(); 
$source->loadXml($xml); 
$xpath = new DOMXpath($source); 
$target = new DOMDocument(); 
$select = $target->appendChild($target->createElement('select')); 

foreach ($xpath->evaluate('/Files/data[type = "Flower"]') as $data) { 
    $option = $select->appendChild($target->createElement('option')); 
    $option->setAttribute('value', $data->getAttribute('id')); 
    $option->appendChild($target->createTextNode($data->getAttribute('id'))); 
} 
echo $target->saveHtml($select); 
0

這是我如何使用答案如果你喜歡,隨意使用代碼。 謝謝!

<?php 
//I have used 2 given answer as example on how i used it. Feel Free to use the code below 
$type = $_GET['type']; 
if(file_exists("xml/data.xml")) { 
$xml = simplexml_load_file('xml/data.xml') or die("Data Missing"); } 
<!-- Code Example 1 --> 
$ids = $xml->xpath('//data[(./Type/text()="'.$type.'")]/@id'); 
<!-- Code Example 2 --> 
$idx = $xml->xpath('/Files/data[normalize-space(Type) = "'.$type.'"]/@id'); 
?> 
<!-- Example 1 --> 
<select> 
    <?php 
//echo $ids[0]; 
foreach ($ids as $id) { 
echo '<option value="'.$id[0].'">'.$id[0].'</option>'; 
} 
?> 
</select> 
<!-- Example 2 --> 
<select> 
    <?php 
//echo $ids[0]; 
foreach ($idx as $id2) { 
echo '<option value="'.$id2[0].'">'.$id2[0].'</option>'; 
} 
?> 
</select> 
<a href="logout.php">Logout 
</a>