如何使用 SimpleDOM SortXPath 对节点值进行排序?

发布于 2024-10-04 11:22:47 字数 484 浏览 0 评论 0原文

XML 新手来了!
我有一个仅包含以下 XML 的文件:

<tags>
 <tag>orange</tag>
 <tag>apple</tag>
 <tag>banana</tag>
</tags>

我想按字母顺序输出标签。
我正在尝试使用 SimpleDOM 库及其 sortedXPath 方法。这是我到目前为止所拥有的,它输出未排序的标签。

$allTags = simpledom_load_file("tags.xml");
foreach ($allTags->sortedXPath("//tags/tag", "tag") as $i => $item)
{
   echo($item);
}

有人可以告诉我如何正确编写它才能起作用吗?干杯!

XML newbie here!
I have a file containing only the following XML:

<tags>
 <tag>orange</tag>
 <tag>apple</tag>
 <tag>banana</tag>
</tags>

I want to ouput the tags alphabetically.
I am trying to use SimpleDOM library and its sortedXPath method. Here's what I have so far, which outputs the tags unsorted.

$allTags = simpledom_load_file("tags.xml");
foreach ($allTags->sortedXPath("//tags/tag", "tag") as $i => $item)
{
   echo($item);
}

Could someone tell me how to write this correctly so it works? Cheers!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌化 2024-10-11 11:22:47

在 XPath 中,您可以使用单个点 . 引用当前节点(称为“上下文节点”),因此如果您要访问 //tags/tag,则必须使用. 获取tag 的值。你的例子变成:

$allTags = simpledom_load_file("tags.xml");
foreach ($allTags->sortedXPath("//tags/tag", ".") as $i => $item)
{
    echo($item);
}

In XPath, you can refer the current node (called "context node") using a single dot . so if you're accessing //tags/tag you have to use . to get the value of tag. Your example becomes:

$allTags = simpledom_load_file("tags.xml");
foreach ($allTags->sortedXPath("//tags/tag", ".") as $i => $item)
{
    echo($item);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文