如何使用 DOM 对 xml 文件进行排序


How to sort a xml file using DOM

我有一个 xml 文件的结构,如下所示

<?xml version="1.0"?>
 <library>
<book id="1003">
    <title>Jquery MVC</title>
    <author>Me</author>
    <price>500</price>
</book>
<book id="1001">
    <title>Php</title>
    <author>Me</author>
    <price>600</price>
</book>
<book id="1002">
    <title>Where to use IFrame</title>
    <author>Me</author>
    <price>300</price>
</book>
</library>

为了根据书籍 ID 对此 xml 进行排序,

从堆栈溢出查看此方法

我像这样编码

$dom = new DOMDocument();
$dom->load('DOM.xml');
$library = $dom->documentElement;
$xpath = new DOMXPath($dom);
$result = $xpath->query('/library/book');
function sort_trees($t1,$t2){
    return strcmp($t1['id'], $t2['id']);    
}
usort($result, 'sort_trees');
print_r($result);*/

但它给了我一个错误

警告:usort() 期望参数 1 是数组,对象在第 24 行的/var/www/html/testphp/phpxml/readxml.php 中给出

你引用的答案是针对SimpleXML的,但你使用的是DOMDocument。

如果你想继续使用DOMDocument,你需要记住它的API。

$dom = new DOMDocument();
$dom->load('DOM.xml');
$xp = new DOMXPath($dom);
$booklist = $xp->query('/library/book');
// Books is a DOMNodeList, not an array.
// This is the reason for your usort() warning.
// Copies DOMNode elements in the DOMNodeList to an array.
$books = iterator_to_array($booklist);
// Second, your sorting function is using the wrong API
// $node['id'] is SimpleXML syntax for attribute access.
// DOMElement uses $node->getAttribute('id');
function sort_by_numeric_id_attr($a, $b)
{
    return (int) $a->getAttribute('id') - (int) $b->getAttribute('id');
}
// Now usort()
usort($books, 'sort_by_numeric_id_attr');
// verify:
foreach ($books as $book) {
    echo $book->C14N(), "'n";
}

如果需要创建节点排序的新输出文档,请创建一个新文档,导入根元素,然后按排序顺序导入 book 节点并添加到文档中。

$newdoc = new DOMDocument('1.0', 'UTF-8');
$libraries = $newdoc->appendChild($newdoc->importNode($dom->documentElement));
foreach ($books as $book) {
    $libraries->appendChild($newdoc->importNode($book, true));
}
echo $newdoc->saveXML();

但是,更好的方法是使用 XSLT:

<?xml version="1.0" encoding="UTF-8" ?>
<!-- file "sort_by_numeric_id.xsl" -->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="UTF-8" method="xml" />
<xsl:template match="node()|@*">
    <xsl:copy><xsl:apply-templates select="node()|@*"/></xsl:copy>
</xsl:template>
<xsl:template match="/*">
    <xsl:copy>
        <xsl:apply-templates select="@*"/>
        <xsl:apply-templates select="*">
            <xsl:sort select="@id" data-type="number"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>

然后使用 XSLTProcessor(或从命令行xsltproc):

$xsltdoc = new DOMDocument();
$xsltdoc->load('sort_by_numeric_id.xsl');
$xslt = new XSLTProcessor();
$xslt->importStyleSheet($xsltdoc);
// You can now use $xslt->transformTo*() methods over and over on whatever documents you want
$libraryfiles = array('library1.xml', 'library2.xml');
foreach ($libraryfiles as $lf) {
    $doc = new DOMDocument();
    $doc->load($lf);
    // write the new document
    $xslt->transformToUri($doc, 'file://'.preg_replace('/('.[^.]+)?$/', '-sorted$0', $lf, 1);
    unset($doc); // just to save memory
}

(从您的重复问题中复制过来)这有效

$dom = new DOMDocument();
$dom->load('dom.xml');
$xp = new DOMXPath($dom);
$booklist = $xp->query('/library/book');
$books = iterator_to_array($booklist);

function sort_by_numeric_id_attr($a, $b)
{
    return (int) $a->getAttribute('id') - (int) $b->getAttribute('id');
}

usort($books, 'sort_by_numeric_id_attr');
$newdom = new DOMDocument("1.0");
$newdom->formatOutput = true;
$root = $newdom->createElement("library");
$newdom->appendChild($root);
foreach ($books as $b) {
    $node = $newdom->importNode($b,true);
    $root->appendChild($newdom->importNode($b,true));
}
$newdom->save('DOM2.xml');

如您所见,您需要创建一个新的 DOMDocument,并将排序后的子项添加到其中(通过 importNode 将 DOMNodes 从一个 DOMDocument 复制到另一个 DOMDocument)。