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 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记