[英]Change the prefix of the root element of an XML with PHP
如何使用 DomDocument 或 SimpleXML 或任何其他庫通過 PHP 更改 XML 的根元素的前綴?
我試過這樣:
$xml = new \SimpleXMLElement($content, \LIBXML_PARSEHUGE, false, "p", true);
或者
$dom = new \DOMDocument();
$response = $dom->loadXML($content);
$root = $dom->documentElement;
$root->setAttributeNS(
'http://www.w3.org/2000/xmlns/',
'xmlns:p',
'p'
);
但它似乎沒有按預期工作。
我期望的結果應該是:
<p:rootElement>
<other>tag</other>
</p:rootElement>
我不確定您是否能夠像在此處嘗試那樣修改根節點。 命名空間 URI 應為http://www.w3.org/2000/xmlns/p
如果您嘗試使用它作為前綴p
並且您將使用p:root
作為qualifiedName 但這將導致根像這樣修改節點<root xmlns:p="http://www.w3.org/2000/xmlns/p" p:root="p"/>
獲得您尋求的輸出的一種可能的替代方法可能是添加一個新節點 - 將原始根中的所有子節點附加到它並刪除原始節點。 誠然,它很hacky
,很可能存在更好的解決方案......
給定源 XML 為:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
<domain>cdiinvest.com.br</domain>
<domain>savba.sk</domain>
<domain>laboratoriodiseno.cl</domain>
<domain>upc.ro</domain>
<domain>nickel.twosuperior.co.uk</domain>
<domain>hemenhosting.org</domain>
<domain>hostslim.eu</domain>
</root>
然后,修改源 XML:
# local XML source file
$file='xml/netblock.xml';
# new node namespace properties
$nsuri='http://www.w3.org/2000/xmlns/p';
$nsname='p:root';
$nsvalue=null;
# create the DOMDocument and load the XML
libxml_use_internal_errors( true );
$dom=new DOMDocument;
$dom->formatOutput=true;
$dom->validateOnParse=true;
$dom->preserveWhiteSpace=false;
$dom->strictErrorChecking=false;
$dom->recover=true;
$dom->load( $file );
libxml_clear_errors();
# create the new root node
$new=$dom->createElementNS( $nsuri, $nsname, $nsvalue );
$dom->appendChild( $new );
# find the original Root
$root=$dom->documentElement;
# iterate backwards through the childNodes - inserting into the new root container in the original order
for( $i=$root->childNodes->length-1; $i >= 0; $i-- ){
$new->insertBefore( $root->childNodes[ $i ],$new->firstChild );
}
# remove original root
$root->parentNode->removeChild( $root );
# save the XML ( or, as here, print out modified XML )
printf('<textarea cols=80 rows=10>%s</textarea>', $dom->saveXML() );
這導致以下輸出:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<p:root xmlns:p="http://www.w3.org/2000/xmlns/p">
<domain>cdiinvest.com.br</domain>
<domain>savba.sk</domain>
<domain>laboratoriodiseno.cl</domain>
<domain>upc.ro</domain>
<domain>nickel.twosuperior.co.uk</domain>
<domain>hemenhosting.org</domain>
<domain>hostslim.eu</domain>
</p:root>
根元素是根元素。 您可以通過使用您選擇的根元素創建一個新文檔來更改它。
如果剩下的工作是從另一個文檔導入所有根元素子元素,那就這樣吧(SimpleXML 不適合,DOMDocument 是,請參閱DOMDocument::importNode
並注意$deep
標志)。
如果您實際上並不想更改根元素而是重寫 XML,那么XMLReader
/ XMLWriter
可能就是您要尋找的。
(您的問題並不完全清楚,因為它錯過了示例的輸入文檔)
與參考 Q&A 進行比較你如何在 PHP 中解析和處理 HTML/XML? .
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.