doukuiqian9911 2016-08-31 07:00
浏览 96
已采纳

使用命名空间创建SimpleXMLElement节点并防止名称空间重复

For a google sitemap I want to create XML nodes with namespace. How can I prevent simplexml from inserting the namespace on each node.

Structure that I need:

<xhtml:link 
             rel="alternate"
             hreflang="de"
             href="http://www.example.com/deutsch/"
             />

Structure from my code:

    <?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
       <url>
          <loc>www.url.ch</loc>
          <xhtml:link xmlns:xhtml="xhtml" rel="alternate" hreflang="de-CH" href="www.url.ch/de">www.url.ch/de</xhtml:link>
          <xhtml:link xmlns:xhtml="xhtml" rel="alternate" hreflang="fr-CH" href="www.url.ch/fr">www.url.ch/fr</xhtml:link>
       </url>
    </urlset>

My Code:

        $rootNode = new SimpleXMLElement(
            '<?xml version="1.0" encoding="utf-8"?>' .
            '   <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"></urlset>'
        );

        $urlNode = $rootNode->addChild('url');
        $urlNode->addChild('loc', 'www.url.ch');

        foreach (['de', 'fr', 'it', 'en'] as $locale) {
            if (in_array($locale, ['it', 'en'])) {
                continue;
            }

            $localeNode = $urlNode->addChild(
                'xhtml:link',
                'www.url.ch' . '/' . $locale,
                'xhtml'
            );

            $localeNode->addAttribute('rel', 'alternate');
            $localeNode->addAttribute('hreflang', $locale . '-CH');
            $localeNode->addAttribute('href', 'www.url.ch' . '/' . $locale);
        }

        $rootNode->saveXML($filePath);
  • 写回答

1条回答 默认 最新

  • douli2063 2016-08-31 09:29
    关注

    You need to specify the namespace in the addChild call as the globally unique "namespace identifier" (URI) not the "local prefix". So in this case, you are binding the xhtml prefix as xmlns:xhtml="http://www.w3.org/1999/xhtml" so the namespace URI is http://www.w3.org/1999/xhtml:

    $localeNode = $urlNode->addChild(
        'xhtml:link',
        'www.url.ch' . '/' . $locale,
        'http://www.w3.org/1999/xhtml'
    );
    

    The XML library then looks up the already-assigned prefix for this namespace when generating the XML, and gives the desired result.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算