【问题标题】:Getting xpath child node value获取 xpath 子节点值
【发布时间】:2012-09-17 03:36:02
【问题描述】:

我无法从下面的 XML 获取文本“TestTwo”,其中父级具有 Name=SN 的属性。我能够获得 SimpleXMLElement,但无法弄清楚如何获得孩子。

返回文本“TestTwo”的最佳方式是什么?

谢谢!

$xml = simplexml_load_string($XMLBELOW);
$xml->registerXPathNamespace('s','urn:oasis:names:tc:SAML:2.0:assertion');
$result = $xml->xpath("//s:Attribute[@Name='sn']");
var_dump( $result);

$XMLBELOW = <<<XML
<?xml version="1.0" ?>
<saml2:Assertion ID="SAML-4324423" IssueInstant="2012-09-24T17:49:39Z" Version="2.0" xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">
  <saml2:Issuer>
    Test
  </saml2:Issuer>
  <saml2:Subject>
    <saml2:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified" NameQualifier="Test">
      Tester
    </saml2:NameID>
    <saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
      <saml2:SubjectConfirmationData NotBefore="2012-09-24T17:48:39Z" NotOnOrAfter="2012-09-24T17:51:39Z"/>
    </saml2:SubjectConfirmation>
  </saml2:Subject>
  <saml2:Conditions NotBefore="2012-09-24T17:48:39Z" NotOnOrAfter="2012-09-24T17:51:39Z"/>
  <saml2:AuthnStatement AuthnInstant="2012-09-24T17:49:39Z" SessionNotOnOrAfter="2012-09-24T17:51:39Z">
    <saml2:SubjectLocality Address="105.57.487.48"/>
    <saml2:AuthnContext>
      <saml2:AuthnContextClassRef>
        urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified
      </saml2:AuthnContextClassRef>
    </saml2:AuthnContext>
  </saml2:AuthnStatement>
  <saml2:AttributeStatement>
    <saml2:Attribute Name="sn" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified">
      <saml2:AttributeValue>
        TestTwo
      </saml2:AttributeValue>
    </saml2:Attribute>
    <saml2:Attribute Name="departmentNumber" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified">
      <saml2:AttributeValue>
        OPERS
      </saml2:AttributeValue>
    </saml2:Attribute>
  </saml2:AttributeStatement>
</saml2:Assertion>
XML;

【问题讨论】:

    标签: php xml xpath simplexml


    【解决方案1】:

    这个怎么样?

    $result = $xml->xpath("//s:Attribute[@Name='sn']/*");
    var_dump( $result[0]->__toString() ); // or just `echo $result[0];`
    

    更新后的表达式将为您获取目标元素的所有子元素(如果您愿意,可以进一步缩小结果集)。

    由于xpath() 方法返回一个数组,您需要获取其中的一些元素,然后在这些对象上调用“toString”来获取其文本。我已经完成了第一个。

    【讨论】:

    • /* 是我忘记的。非常感谢您的快速解决方案!
    猜你喜欢
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 2023-03-16
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多