代码之家  ›  专栏  ›  技术社区  ›  MB34

php-删除XML空节点

  •  0
  • MB34  · 技术社区  · 6 年前

    我发现此代码用于从和XML文件中删除空节点,但它无法正常工作。它会留下一个真正需要删除的空节点。是的,它是空的,只是里面有空白。

    $domxml = new DOMDocument('1.0');
    $domxml->preserveWhiteSpace = false;
    $domxml->formatOutput = true;
    $domxml->loadXML($this->response);
    $this->response = $domxml->saveXML($domxml->documentElement);
    

    有人知道更好的方法吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   ThW    6 年前

    normalize-space()

    //*


    • normalize-space(.) = ""

    • not(@*)

    • not(.//node()[normalize-space(.) != ""])

    • not(.//*[@*])

    • parent::*

    $xml = <<<'XML'
    <foo>
      <bar></bar>
      <bar>123</bar>
      <bar foo="123"></bar>
      <bar><foo>   </foo></bar>
      <bar><!-- test --></bar>
    </foo>
    XML;
    
    $document = new DOMDocument();
    $document->preserveWhiteSpace = FALSE;
    $document->formatOutput = TRUE; 
    $document->loadXml($xml);
    $xpath = new DOMXpath($document);
    
    $expression = 
      '//*[
        normalize-space(.) = "" and 
        not(@*) and  
        not(.//node()[normalize-space(.) != ""]) and 
        not(.//*[@*]) and
        parent::*
      ]';
    
    $nodes = $xpath->evaluate($expression);
    for ($i = $nodes->length - 1; $i >= 0; $i--) {
      $nodes[$i]->parentNode->removeChild($nodes[$i]);
    }
    
    echo $document->saveXml();
    

    <?xml version="1.0"?>
    <foo>
      <bar>123</bar>
      <bar foo="123"/>
      <bar>
        <!-- test -->
      </bar>
    </foo>
    
        2
  •  0
  •   Parfait    6 年前

    * [.='']

    XSLT Fiddle Demo

    <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output version="1.0" encoding="UTF-8" indent="yes" />
    <xsl:strip-space elements="*"/>
    
      <!-- Identity Transform to Copy Document as is -->
      <xsl:template match="@*|node()">
        <xsl:copy>
          <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
      </xsl:template>
    
      <!-- Empty Template to Remove Empty Nodes -->
      <xsl:template match="*[.='']"/>
    
    </xsl:transform>
    

    // LOAD XML
    $xml = new DOMDocument('1.0', 'UTF-8');
    $xml->load('Input.xml');
    
    // LOAD XSLT 
    $xsl = new DOMDocument('1.0', 'UTF-8');   
    $xsl->load('XSLT_Script.xsl');
    
    // INITIALIZE TRANSFORMER
    $proc = new XSLTProcessor;
    $proc->importStyleSheet($xsl);
    
    // RUN TRANSFORMATION
    $newXML = $proc->transformToXML($xml);
    
    // SAVE NEW TREE TO FILE
    echo $newXML;
    file_put_contents('Output.xml', $newXML);