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

使用XMLWriter跟踪命名空间声明

  •  3
  • Evert  · 技术社区  · 17 年前

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

    谢谢,

    2 回复  |  直到 17 年前
        1
  •  7
  •   commonpike    14 年前

    您可以在文档中的所需位置写下命名空间一次,例如在top元素中:

    $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
  •  6
  •   VolkerK    17 年前

    <?php
    $w = new XMLWriter;
    $w->openMemory();
    $w->setIndent(true);
    $w->startElementNS('foo', 'bar', 'http://whatever/foo');
    $w->startElementNS('foo', 'baz', null);
    $w->endElement();
    $w->endElement();
    echo $w->outputMemory();
    打印
    <foo:bar xmlns:foo="http://whatever/foo">
     <foo:baz/>
    </foo:bar>