Xpath for Find &代替? [英] Xpath for Find & Replace?

查看:52
本文介绍了Xpath for Find &代替?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

各位论坛成员,我是 Xpath 的新手,有以下问题.例如,假设我有 300 个单独的 XML 文件,我需要进行可能仅影响 40 个 XML 文件的全局文本更改.是否可以使用 Xpath 执行查找和操作?在所有 300 个 XML 文件之间进行替换操作?比如说,我需要全局更改的单词是这些单词,LBRT Assembly"更改为LBRS assembly".Xpath 是否提供执行此类操作的能力?我知道 Xpath 擅长查询 XML 元素.但是,它也可以执行查找和替换操作吗?可以使用的最佳应用程序是什么,可以帮助编写复杂的 Xpath 查询命令?任何意见将受到极大欢迎.提前致谢.

Fellow Forum Members, I'm new to Xpath and have the following question. Let's say for example I have 300 separate XML files and I need to make a global text change that may impact only 40 of the XML files. Is it possible using Xpath to perform a find & replace operation among all 300 XML files? Let's say for example the words I need to globally change are these words, "LBRT Assembly" change to "LBRS assembly". Does Xpath offer the ability to perform such an operation? I know Xpath is good at querying XML elements. However, can it also perform a find and replace operation? What is the best application available one can use that will assist one in coding complex Xpath query commands? Any opinion will be greatly welcomed. Thanks in advance.

推荐答案

XPath 无法修改 XML 文件.为此,您需要 XSLT 或 XQuery.

XPath cannot modify an XML file. For that you need XSLT or XQuery.

如果这确实是一个全局更改(也就是说,如果您想更改此文本,而不管它出现在什么上下文中),那么我自己会非常倾向于使用文本编辑器来执行此操作:这与我的建议背道而驰总是说在处理 XML 数据时应该使用 XML 工具.但是,如果找到要更改的文本确实取决于 XML 上下文,我会编写一个小 XSLT 2.0 程序来完成它:它可能大约有十几行.核心是:

If this really is a global change (that is, if you want to change this text regardless of the context where it appears) then I would be very inclined myself to do it using a text editor: that goes against the advice I invariably give which says when processing XML data you should use XML tools. But if finding the text to change does depend on the XML context, I would write a little XSLT 2.0 program to do it: it's probably about a dozen lines. The core would be:

(a) 一个标准的身份模板来复制元素不变

(a) a standard identity template to copy elements unchanged

<xsl:template match="*">
  <xsl:copy-of select="@*"/>
  <xsl:apply-templates select="node()"/>
</xsl:template>

(b) 驱动处理的东西:

(b) something to drive the processing:

<xsl:template name="main">
  <xsl:apply-templates select="collection('my/dir/?select=*.xml')"/>
</xsl:template>

(e) 为每个输入文档创建一个新的输出文档的模板

(e) a template to create a new output document for each input document

<xsl:template match="/">
  <xsl:result-document href="{replace(document-uri(.), '/dir/', '/outdir/')}">
    <xsl:apply-templates/>
  </xsl:result-document>
</xsl:template> 

(d) 修改文本节点的模板

(d) a template to modify the text nodes

<xsl:template match="text()">
  <xsl:value-of select="replace(., 'xxx', 'yyy')"/>
</xsl:template>

这篇关于Xpath for Find &amp;代替?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆