【问题标题】:Adding Prefix / Namespace to XML将前缀/命名空间添加到 XML
【发布时间】:2017-02-28 13:40:42
【问题描述】:

我已经生成了一个简单的 xml。我想在 xml 中添加命名空间/前缀有没有使用 php DomDocument 的方法。还是我需要使用core php替换标签并在xml中重新创建。

<?xml version="1.0" encoding="UTF-8"?>
<orderShipment>
    <orderData>
        <productId>1</productId>
        <orderStatus>
            <status>Shipped</status>
            <statusQuantity>
                <amount>1</amount>
            </statusQuantity>
            <trackingInfo>
                <shipDateTime>Fri, 24 Feb 2017</shipDateTime>
                <carrierName>UPS</carrierName>
                <methodCode>Standard</methodCode>
                <trackingNumber>123123123</trackingNumber>
                <trackingURL>http://ups.com</trackingURL>
            </trackingInfo>
        </orderStatus>
    </orderData>
</orderShipment>

预期输出

<?xml version="1.0" encoding="UTF-8"?>
<ns2:orderShipment>
    <ns2:orderData>
        <ns2:productId>1</ns2:productId>
        <ns2:orderStatus>
            <ns2:status>Shipped</ns2:status>
            <ns2:statusQuantity>
                <ns2:amount>1</ns2:amount>
            </ns2:statusQuantity>
            <ns2:trackingInfo>
                <ns2:shipDateTime>Fri, 24 Feb 2017</ns2:shipDateTime>
                <ns2:carrierName>UPS</ns2:carrierName>
                <ns2:methodCode>Standard</ns2:methodCode>
                <ns2:trackingNumber>123123123</ns2:trackingNumber>
                <ns2:trackingURL>http://ups.com</ns2:trackingURL>
            </ns2:trackingInfo>
        </ns2:orderStatus>
    </ns2:orderData>
</ns2:orderShipment>

【问题讨论】:

    标签: php xml domdocument


    【解决方案1】:

    使用DOMDocument::createElementNS() 方法。

    $namespaceUri = 'http://www.ups.com/WSDL/XOLTWS/Track/v2.0';
    
    $document = new DOMDocument();
    $order = $document->appendChild(
      $document->createElementNS($namespaceUri, 'ns2:orderShipment')
    );
    $order->appendChild(
      $document->createElementNS($namespaceUri, 'ns2:orderData')
    );
    
    $document->formatOutput = TRUE;
    echo $document->saveXml();
    

    输出:

    <?xml version="1.0"?>
    <ns2:orderShipment xmlns:ns2="http://www.ups.com/WSDL/XOLTWS/Track/v2.0">
      <ns2:orderData/>
    </ns2:orderShipment>
    

    *NS 是 DOM 方法的命名空间感知变体。通常他们会将命名空间 uri 作为第一个参数。命名空间前缀只会在“write/setter”方法中使用。

    【讨论】:

    • 对于所有其他子元素,我是否需要使用相同的格式,即 CreateElementNS.正如我所看到的,它附加了属性xmlns:ns2="http://www.ups.com/WSDL/XOLTWS/Track/v2.0。我不想要子元素。
    • 我添加了orderData 孩子。如您所见,它不会再次附加命名空间定义。仅当您在将子节点附加到其父节点之前使用它时,才会发生额外的命名空间定义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    相关资源
    最近更新 更多