2016-10-18 7 views
0

属性「ロール」(この場合「学生」)のセカンド値のみを取得するにはどうすればよいですか?phpを使用してXMLの属性の2番目の値を取得する

<saml:Attribute Name="Role"> 
    <saml:AttributeValue xsi:type="xs:string">Master</saml:AttributeValue> 
    <saml:AttributeValue xsi:type="xs:string">Student</saml:AttributeValue> 
</saml:Attribute> 

答えて

0

サンプルxmlを少し拡張し、それを文字列にロードして、適用されているxpath式の効果を確認しました。また、xmlファイルで使用されているすべてのネームスペースを登録する必要があることにも注意してください。接頭辞はxmlと一致する必要はありませんが、登録された接頭辞はxpath式で使用する必要があります。

<?php 
$string = <<<XML 
<root xmlns:saml="http://example.org" xmlns:xs="http://www.w3.org/2001/XMLSchema" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<saml:Attribute Name="Role"> 
    <saml:AttributeValue xsi:type="xs:string">Master</saml:AttributeValue> 
    <saml:AttributeValue xsi:type="xs:string">Student1</saml:AttributeValue> 
</saml:Attribute> 
<saml:Attribute Name="Unknown"> 
    <saml:AttributeValue xsi:type="xs:string">Zero</saml:AttributeValue> 
    <saml:AttributeValue xsi:type="xs:string">One</saml:AttributeValue> 
</saml:Attribute> 
<saml:Attribute Name="Role"> 
    <saml:AttributeValue xsi:type="xs:string">Master</saml:AttributeValue> 
    <saml:AttributeValue xsi:type="xs:string">Student2</saml:AttributeValue> 
</saml:Attribute> 
</root> 
XML; 

$xml = new SimpleXMLElement($string); 
$xml->registerXPathNamespace('a','http://www.w3.org/2001/XMLSchema'); 
$xml->registerXPathNamespace('b','http://www.w3.org/2001/XMLSchema-instance'); 
$xml->registerXPathNamespace('s','http://example.org'); 

$result = $xml->xpath('//s:Attribute[@Name="Role"]/s:AttributeValue[2]'); 

foreach ($result as $a) 
{ 
print $a . "\n"; 
} 

?> 
関連する問題