【问题标题】:Tracking namespace declarations with XMLWriter使用 XMLWriter 跟踪命名空间声明
【发布时间】:2010-11-03 02:20:16
【问题描述】:

我正在开发一个 XML 网络服务(在 PHP 中!),为了做“正确”的事情,我想使用 XMLWriter 而不是仅仅连接字符串并希望获得最好的结果。

我在任何地方都使用 XML 命名空间,使用 ->startElementNS 和 ->writeElementNS。问题是,每次我使用这些函数时,都会写入一个新的命名空间声明。

虽然这是正确的语法,但它有点不必要。我想确保我的命名空间声明仅在第一次在文档上下文中使用时编写。

有没有一种简单的方法可以使用 XMLWriter 来解决这个问题,或者我是否坚持将其子类化并手动管理它。

谢谢, 埃弗特

【问题讨论】:

    标签: php xml namespaces xmlwriter


    【解决方案1】:

    您可以在文档中的所需位置写出命名空间一次,f.e.在顶部元素中:

    $writer = new XMLWriter(); 
    $writer->openURI('php://output'); 
    $writer->startDocument('1.0'); 
    
    $writer->startElement('sample');            
    $writer->writeAttributeNS('xmlns','foo', null,'http://foo.org/ns/foo#');
    $writer->writeAttributeNS('xmlns','bar', null, 'http://foo.org/ns/bar#');
    
    $writer->writeElementNS('foo','quz', null,'stuff here');
    $writer->writeElementNS('bar','quz', null,'stuff there');
    
    $writer->endElement();
    $writer->endDocument();
    $writer->flush(true);
    

    这应该会像

    <?xml version="1.0"?>
    <sample xmlns:foo="http://foo.org/ns/foo#" xmlns:bar="http://foo.org/ns/bar#">
     <foo:quz>stuff here</foo:quz>
     <bar:quz>stuff there</bar:quz>
    </sample>
    

    令人讨厌的 xmlwriter 不会跟踪这些声明 - 它允许您编写无效的 xml。需要属性也很烦人,即使它可以为 null - 而且它是第三个参数,而不是最后一个。

    $2c, *-派克

    【讨论】:

      【解决方案2】:

      您可以将 NULL 作为 uri 参数传递。

      <?php
      $w = new XMLWriter;
      $w->openMemory();
      $w->setIndent(true);
      $w->startElementNS('foo', 'bar', '@987654321@');
      $w->startElementNS('foo', 'baz', null);
      $w->endElement();
      $w->endElement();
      echo $w->outputMemory();
      打印

      【讨论】:

      • 不是我想要的。在您的示例中,“bar”和“baz”元素可能由完全不同的对象和方法实现,它们并不总是相互了解。我总是想指定命名空间,但我想它只渲染第一次。
      • 我在 php/xmlwriter 或 libxml/xmlwriter 中没有找到对此的支持。您可能必须自己跟踪这一点。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多