使用带名称空间的SimpleXML删除子元素

时间:2013-02-21 16:14:10

标签: php xml simplexml

XML:

<?xml version="1.0"?>
<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="_9069a2d7-491f-49ca-a13f-96c5bad39b14" IssueInstant="2010-04-06T16:27:34Z" Version="2.0">
  <saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://ssl.perquisite.net/memberweb/federation</saml:Issuer>
  <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    <SignedInfo>
      <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
      <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
      <Reference URI="#_9069a2d7-491f-49ca-a13f-96c5bad39b14">
        <Transforms>
          <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
          <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
            <InclusiveNamespaces xmlns="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="#default saml ds xs xsi"/>
          </Transform>
        </Transforms>
        <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
        <DigestValue>QpoCI6jZFhQi+PuYM6UaFBL9KEU=</DigestValue>
      </Reference>
    </SignedInfo>
    <SignatureValue>X8X6qSUDKa3h3+/girXCeOVxo8=</SignatureValue>
    <KeyInfo>
      <X509Data>
        <X509Certificate>MIIB2...CieOpEo35g==</X509Certificate>
      </X509Data>
    </KeyInfo>
  </Signature>
  <saml:Subject>
    <saml:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient">654d2065-6eed-401f-bf6d-a181117a5fb8</saml:NameID>
  </saml:Subject>
  <saml:Conditions NotBefore="2010-04-06T16:27:04Z" NotOnOrAfter="2010-04-06T16:28:04Z"/>
  <saml:AuthnStatement AuthnInstant="2010-04-06T16:27:34Z">
    <saml:AuthnContext>
      <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:X509</saml:AuthnContextClassRef>
    </saml:AuthnContext>
  </saml:AuthnStatement>
</saml:Assertion>

代码:

$xml设置为上面的xml。

$sxml = new SimpleXMLElement($xml);
$sxml->registerXPathNamespace('saml', 'urn:oasis:names:tc:SAML:2.0:assertion');
$sxml->registerXPathNamespace('sig', 'http://www.w3.org/2000/09/xmldsig#');

$signodes = $sxml->xpath('/saml:Assertion/sig:Signature');

此时我想删除sig:Signature节点和来自的所有子节点 XML。我试过了:

$node = dom_import_simplexml($signodes[0]);
$node->parentNode->removeChild($node);

foreach($signodes as $item) {
    $node = dom_import_simplexml($item);
    $node->parentNode->removeChild($node);
}

unset($signodes);

foreach($signodes as $node) {
   unset($node);
}

然后使用以下命令取回XML:

$Canonical = $sxml->asXML();

以上所有内容似乎都对生成的XML没有影响 (但也不要给错误。)

任何人都有任何线索,为什么?

1 个答案:

答案 0 :(得分:0)

正如你看到mkaatman所说的那样, php有一个方法removeChild。 (http://php.net/manual/en/domnode.removechild.php

您可以通过示例删除子项: $节点 - &GT; parentNode-&GT; removeChild之($节点);