douchan4674 2016-08-09 07:46
浏览 44
已采纳

PHP - 在DOMDocument中包含DOMDocumentFragment和未定义的命名空间

MasetrPage.xml:

<?xml version="1.0" encoding="UTF-8"?>
<PAGE
xmlns:PHOENIX = 'PHOENIX'
xmlns:PHOENIX.CORE = 'PHOENIX/CORE'
xmlns:PHOENIX.CORE.PAGE = 'PHOENIX/CORE/PAGE'
xmlns:PHOENIX.CORE.COMPILER = 'PHOENIX/CORE/COMPILER'
>
</PAGE>

Page.xml:

<PHEONIX.CORE:EXAMPLE.ELEMENT />
<PHEONIX.CORE:EXAMPLE.ELEMENT2 />

Now I want to include the Page.xml content inside the MasterPage.xml PAGE tag.

My PHP Code:

//[i] Initialize new \DOMDocument from from PageMaster.xml.
$pageDocument = \DOMDocument::load('PageMaster.xml');

//[i] Create fragment from pageDocument and append content from page XML.
$pageDocument_frag = $pageDocument->createDocumentFragment();
$pageDocument_frag->appendXML(file_get_contents('Page.xml'));

But here I get an error that the namespaces are not defined inside the Page.xml. But for my project I don't want to define the namespaces inside the Page.xml

  • 写回答

1条回答 默认 最新

  • douhui8163 2016-08-09 08:15
    关注

    If you don't define the namespaces inside the fragment string then it will not be valid XML. Namespace prefixes are both exchangeable and optional. The prefixes do not define the namespace, the xmlns*-attributes do.

    The following 3 examples all parse to the same namespace and local node name:

    • <f:foo xmlns:f="urn:foo-ns"/>
    • <foo:foo xmlns:foo="urn:foo-ns"/>
    • <foo xmlns="urn:foo-ns"/>

    All result in an element node with the local name foo and the namespace urn:foo-ns. You can read the node name as {urn:foo-ns}foo.

    However to make the XML input for users easier you can define a set prefixes for you namespaces. You take the input an wrap it into an tag that defines the namespace. After that you can parse it as a fragment and copy the childnodes.

    $xhtml = <<<'XHTML'
      <div>
        <p>Some Content.</p>
      </div>
    XHTML;
    
    $document = new DOMDocument();
    $import = $document->createDocumentFragment(); 
    $import->appendXml(
      '<section xmlns="http://www.w3.org/1999/xhtml">'.$xhtml.'</section>'
    );
    $fragment = $document->createDocumentFragment();
    foreach ($import->childNodes->item(0)->childNodes as $node) {
      $fragment->appendChild($node->cloneNode(TRUE));
    }
    
    $document->formatOutput = TRUE;
    echo $document->saveXml($fragment);
    

    Output:

    <div xmlns="http://www.w3.org/1999/xhtml">
      <p>Some Content.</p>
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?