gpt4 book ai didi

php - 我可以使用XPath或诸如正则表达式之类的东西从XML中提取数据吗?

转载 作者:行者123 更新时间:2023-12-03 17:12:45 25 4
gpt4 key购买 nike

当然,我可以使用正则表达式来解析XML中的数据。

<?xml version="1.0"?>
<definitions>
<message name="notificationInput">
<part name="body" element="xsd:notificationRequest" />
</message>
<message name="notificationOutput">
<part name="body" element="xsd:notificationResponse" />
</message>
</definitions>


像这样的模式

/<message.*name="(.*)".*part.*name=".*".*element="xsd:(.*)".*<\/message>/sUg


可能会给我我想要的数据,这里显示为PHP数组:

array(
array("notificationInput", "body", "notificationRequest"),
array("notificationOutput", "body", "notificationResponse")
)


当然,这是非常麻烦且容易出错的。

我知道如何使用 XPath来查询完整的节点,但是我想我不能告诉它“我想要节点 name中的属性 element/definitions/message/part,并且对于每个结果,我也都希望属性 name来自其父”。

现在,我想知道是否可以使用某种语言或技术(最好是PHP中的实现)来指定要提取的数据。

换句话说,我正在寻找一种可以配置而不是编程的解决方案,因为我有很多类似的定义可以提取。

最佳答案

这个简短的XPath 1.0表达式选择了所有需要的属性节点:

/*//*/@*


然后对于每个选定的节点,您都可以使用PHP(我不知道)获取其字符串值。



如果可以使用XPath 2.0,则通过评估类似的表达式来生成所有需要的值:

/*//*/@*/data(.)


这是一个简单的XSLT 2.0转换,它仅计算上述表达式并输出结果:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="/">
<xsl:sequence select="/*//*/@*/data(.)"/>
</xsl:template>
</xsl:stylesheet>


在提供的XML文档上应用此转换时:

<definitions>
<message name="notificationInput">
<part name="body" element="xsd:notificationRequest" />
</message>
<message name="notificationOutput">
<part name="body" element="xsd:notificationResponse" />
</message>
</definitions>


产生想要的结果:

notificationInput body xsd:notificationRequest notificationOutput body xsd:notificationResponse

关于php - 我可以使用XPath或诸如正则表达式之类的东西从XML中提取数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30428550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com