php DomDocument +直接访问xml元素

发布于 2024-12-22 01:22:49 字数 634 浏览 2 评论 0原文

任何人都可以建议我可以查看“Column Name=Error”是否存在的最快、资源占用最少的方法吗?

我不想解析文档,而只是检查元素是否存在。

提前致谢,

<?xml version="1.0" encoding="UTF-8"?>
<Table>
<Columns Items="4">
<Column Name="Error" Type="String" />
<Column Name="Description" Type="String" />
<Column Name="Cause" Type="String" />
<Column Name="Resolution" Type="String" />
</Columns>
<Rows Items="1">
<Row Error="2" Description="Unknown key" Cause="Unknown key" Resolution="Please check     the key is correct, it should be the in form AA11-AA11-AA11-AA11." />
</Rows>
</Table>

Can anyone advise on the fastest, least resource intensive method by which I can see whether 'Column Name=Error' exists please?

I don't want to parse the document, but simply check if elements exist.

Thanks in advance,

<?xml version="1.0" encoding="UTF-8"?>
<Table>
<Columns Items="4">
<Column Name="Error" Type="String" />
<Column Name="Description" Type="String" />
<Column Name="Cause" Type="String" />
<Column Name="Resolution" Type="String" />
</Columns>
<Rows Items="1">
<Row Error="2" Description="Unknown key" Cause="Unknown key" Resolution="Please check     the key is correct, it should be the in form AA11-AA11-AA11-AA11." />
</Rows>
</Table>

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

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

发布评论

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

评论(2

岁月打碎记忆 2024-12-29 01:22:49

正如其他人所提到的,最不占用资源的方法是简单的 strpos() 调用,尽管如果 XML 的确切格式发生变化,这可能会出错。一个完整的方法是使用 DOM,那么你可以尝试 xpath 查询......

$xml = '...'
$dom = new DomDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);

// returns NULL if no columns found with name="error"
$err = $xpath->query('//Column[@Name="Error"]')->item(0);

if ($err) {
  // there is a column with attribute Name="Error"
}

As others have mentioned, the least resource intensive would be a simple strpos() call, though that's subject to error if the exact format of the XML ever changes. A fullproof way is to use DOM, then you could try an xpath query ...

$xml = '...'
$dom = new DomDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);

// returns NULL if no columns found with name="error"
$err = $xpath->query('//Column[@Name="Error"]')->item(0);

if ($err) {
  // there is a column with attribute Name="Error"
}
淡笑忘祈一世凡恋 2024-12-29 01:22:49

你有没有想过简单地使用strpos

$xml= //xml data

if(strpos($xml,'<Column Name="Error"') !== false){
    // its been found
}

编辑:添加 !==false 以允许 0 索引情况(无论如何这里不应该发生)

have you thought of simply using strpos?

$xml= //xml data

if(strpos($xml,'<Column Name="Error"') !== false){
    // its been found
}

edit: added !==false to allow for the 0 index situation (which shouldnt happen here anyways)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文