gpt4 book ai didi

xml - 使用 XPATH 和 XSLT 根据属性值的某些相等条件在 XML 中提取相关的不同元素标签

转载 作者:数据小太阳 更新时间:2023-10-29 02:36:27 24 4
gpt4 key购买 nike

我需要使用 XPATH 和 XSLT 以某种特定方式从 XML 中提取数据

<data>      
<person id="p1">
<name>User1</name>
</person>
<person id="p2">
<name>User2</name>
</person>
<person id="p3">
<name>User3</name>
</person>
<employee eid="emp1" pid="p1">
<dept>dept1</dept>
</employee>
<employee eid="emp2" pid="p3">
<dept>dept3</dept>
</employee>
<employee eid="emp3" pid="p2">
<dept>dept1</dept>
</employee>
</data>

在上面的示例中,我需要为每个人创建 XML,并在输出 xml 中创建相应的 Employee 元素。这两个xml之间的链接是

person.id = employee.pid

喜欢XML1:

<person id="p1">         
<name>User1</name>
</person>
<employee eid="emp1" pid="p1">
<dept>dept1</dept>
</employee>

XML2:

<person id="p2">         
<name>User2</name>
</person>
<employee eid="emp3" pid="p2">
<dept>dept1</dept>
</employee>

XML3:

<person id="p3">         
<name>User3</name>
</person>
<employee eid="emp2" pid="p3">
<dept>dept3</dept>
</employee>

我试了很多方法都无法得到这个。

谢谢...

最佳答案

XPath 是一种用于 XML 文档的查询语言——因此 XPath 表达式的计算不能修改现有文档或创建新的 XML 文档

使用 XSLT 2.0 可以最好地实现您想要的(如果只需要一个结果文档,则使用 XSLT 1.0):

<xsl:stylesheet version="2.0"   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="kEmpByPid" match="employee" use="@pid"/>

<xsl:template match="person">
<xsl:result-document href="file:///c:/temp/delete/XML{position()}">
<t>
<xsl:copy-of select=".|key('kEmpByPid', @id)"/>
</t>
</xsl:result-document>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>

当此 XSLT 2.0 转换应用于提供的 XML 文档时:

<data>
<person id="p1">
<name>User1</name>
</person>
<person id="p2">
<name>User2</name>
</person>
<person id="p3">
<name>User3</name>
</person>
<employee eid="emp1" pid="p1">
<dept>dept1</dept>
</employee>
<employee eid="emp2" pid="p3">
<dept>dept3</dept>
</employee>
<employee eid="emp3" pid="p2">
<dept>dept1</dept>
</employee>
</data>

在“c:\temp\delete”中创建了以下三个 XML 文档:

XML1:

<t>
<person id="p1">
<name>User1</name>
</person>
<employee eid="emp1" pid="p1">
<dept>dept1</dept>
</employee>
</t>

XML2:

<t>
<person id="p2">
<name>User2</name>
</person>
<employee eid="emp3" pid="p2">
<dept>dept1</dept>
</employee>
</t>

XML3:

<t>
<person id="p3">
<name>User3</name>
</person>
<employee eid="emp2" pid="p3">
<dept>dept3</dept>
</employee>
</t>

关于xml - 使用 XPATH 和 XSLT 根据属性值的某些相等条件在 XML 中提取相关的不同元素标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12980257/

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