[英]Replace an attribute in xml with xpath
I want to take an attribute found thru xpath and replace it in the Document. 我想将通过xpath找到的属性替换为Document。
This is the xml: 这是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>
With Java, I can retrieve the value like this: 使用Java,我可以像这样检索值:
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");
This prints out: 255 打印输出:255
So, what XPath function will allow me to replace the 255, for another string? 那么,什么XPath函数可以让我将255替换为另一个字符串? Or do I need something other than XPath for this?
还是我需要XPath以外的其他东西?
So, what XPath function will allow me to replace the 255, for another string?
那么,什么XPath函数可以让我将255替换为另一个字符串? Or do I need something other than XPath for this?
还是我需要XPath以外的其他东西?
XPath is the query language for XML and as such cannot modify an XML document . XPath是XML的查询语言,因此不能修改XML文档 。
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. 为了修改XML文档,需要使用承载XPath的编程语言(例如XSLT,C#,JS,PHP等)。
Here is a solution, where the hosting language is XSLT : 这是一个托管语言为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>
when this transformation is applied on the provided XML 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>
the wanted, correct result is produced : 产生想要的正确结果 :
<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 is a query language for extracting information out of an XML file. XPath是一种查询语言,用于从XML文件中提取信息。 As far as I know it is not suited for replacing or editing data in an XML.
据我所知,它不适合替换或编辑XML中的数据。 One way to transform an XML is via XSLT.
转换XML的一种方法是通过XSLT。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.