用 xpath 替换 xml 中的属性 [英] Replace an attribute in xml with xpath

查看:28
本文介绍了用 xpath 替换 xml 中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取通过 xpath 找到的属性并在文档中替换它.

I want to take an attribute found thru xpath and replace it in the Document.

这是xml:

<MineX STATE="add">
  <Desc F_CREATOR="admin" F_ENTRYDATE="2010-12-24" F_HEIGHT="0.875" F_ID="1" F_LEFT="1.15625" F_LINE_COLOR="255" F_FORECOLOR="0">
    <F_CUSTOM_BYTES></F_CUSTOM_BYTES>
  </Desc>
</MineX>

使用 Java,我可以像这样检索值:

With Java, I can retrieve the value like this:

org.w3c.dom.Document xmlDoc = getDoc(path);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();

XPathExpression myExp = xpath.compile("//MineX/Desc/@F_LINE_COLOR");
System.out.println("Line color:" + (String)myExp.evaluate(xmlDoc, XPathConstants.STRING) + "\n");

打印出来:255

那么,什么 XPath 函数可以让我将 255 替换为另一个字符串?或者我需要 XPath 以外的其他东西吗?

So, what XPath function will allow me to replace the 255, for another string? Or do I need something other than XPath for this?

推荐答案

那么,什么 XPath 函数将允许我更换 255,换另一个细绳?或者我需要别的东西吗与 XPath 相比?

So, what XPath function will allow me to replace the 255, for another string? Or do I need something other than XPath for this?

XPath 是 XML 的查询语言,因此不能修改 XML 文档.

为了修改 XML 文档,需要使用承载 XPath 的编程语言(例如 XSLT、C#、JS、PHP 等).

In order to modify an XML document one needs to use the programming language (such as XSLT, C#, JS, PHP, ..., etc) that is hosting XPath.

这是一个解决方案,其中托管语言是 XSLT:

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

 <xsl:param name="pNewLineColor" select="123"/>

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

 <xsl:template match="@F_LINE_COLOR">
  <xsl:attribute name="{name()}">
    <xsl:value-of select="$pNewLineColor"/>
  </xsl:attribute>
 </xsl:template>
</xsl:stylesheet>

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

<MineX STATE="add">
    <Desc F_CREATOR="admin"
          F_ENTRYDATE="2010-12-24"
          F_HEIGHT="0.875"
          F_ID="1"
          F_LEFT="1.15625"
          F_LINE_COLOR="255"
          F_FORECOLOR="0">
        <F_CUSTOM_BYTES></F_CUSTOM_BYTES>
    </Desc>
</MineX>

产生想要的、正确的结果:

<MineX STATE="add">
    <Desc F_CREATOR="admin"
          F_ENTRYDATE="2010-12-24"
          F_HEIGHT="0.875"
          F_ID="1"
          F_LEFT="1.15625"
          F_LINE_COLOR="123"
          F_FORECOLOR="0">
        <F_CUSTOM_BYTES></F_CUSTOM_BYTES>
    </Desc>
</MineX>

这篇关于用 xpath 替换 xml 中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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