gpt4 book ai didi

c - libxml2 - xpath 和更新属性

转载 作者:行者123 更新时间:2023-11-30 14:47:11 24 4
gpt4 key购买 nike

我有两个 xml 文件,A 和 B,它们具有相同的架构。

A.xml

<books>
<book name="Alice in Wonderland" />
</books>

B.xml

<books>
<book name="Of Mice and Men" />
<book name="Harry Potter" />
</books>

我想在 B.xml 的图书列表中添加属性 source="B",然后将该列表复制到 A.xml,这样 A.xml 就会如下所示

<books>
<book name="Alice in Wonderland" />
<book name="Of Mice and Men" source="B" />
<book name="Harry Potter" source="B" />
</books>

我可以使用xpath从B获取书籍的xpath对象,添加属性,然后将节点集复制到A吗?如果是这样,代码会是什么样子?有没有比 xpath 更好的方法从 B 获取书籍?

最佳答案

我想最简单的方法是使用 XSLT 处理器。对于此任务,XSLT-1.0 处理器就足够了。您可以使用以下模板“合并”这两个文件。只需将 XSLT 处理器与参数 a.xslta.xml 结合使用即可。第二个文件名在 a.xslt 中指定。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
<!-- This is the base filename of the second file without the extension '.xml' -->
<xsl:variable name="secondXMLFile" select="'b'" />
<!-- This changes the second filename to uppercase -->
<xsl:variable name="secondName" select="translate($secondXMLFile,'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')" />
<!-- This adds the filename extension '.xml' to the base filename and creates a document() node -->
<xsl:variable name="second" select="document(concat($secondXMLFile,'.xml'))" />

<!-- identity template --> <!-- This copies all elements from the first file -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>

<!-- modified identity template for second/other document -->
<xsl:template match="*" mode="sec"> <!-- This copies all 'book' elements from the second file -->
<xsl:element name="{name()}">
<xsl:apply-templates select="@*" />
<xsl:attribute name="source"><xsl:value-of select="$secondName" /></xsl:attribute>
<xsl:apply-templates select="node()" />
</xsl:element>
</xsl:template>

<xsl:template match="/books"> <!-- This initiates the copying of both files -->
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
<xsl:apply-templates select="$second/books/*" mode="sec" />
</xsl:copy>
</xsl:template>

</xsl:stylesheet>

关于c - libxml2 - xpath 和更新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51543510/

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