我想更改xml文档中某些元素的属性。什么是最简单的方法? (Xquery是最好的,或者我可以以某种方式处理python)
将/root/person[1]/@name
更改为"Jim"
将/root/person[2]/@name
更改为"John"
sample.xml中
<root>
<person name="brian">
<number>1</number>
<school>Y</school>
<age>18</age>
</person>
<person name="brian">
<number>1</number>
<school>Y</school>
<age>18</age>
</person>
</root>
Sampe_result.xml
<root>
<person name="Jim">
<number>1</number>
<school>Y</school>
<age>18</age>
</person>
<person name="John">
<number>1</number>
<school>Y</school>
<age>18</age>
</person>
</root>
答案 0 :(得分:1)
在XSLT中最容易实现对XML文档的小改动:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- By default, copy elements and attributes unchanged -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node() | @*"/>
</xsl:copy>
</xsl:template>
<!-- Change /root/person[1]/@name to "Jim" -->
<xsl:template match="/root/person[1]/@name">
<xsl:attribute name="name">Jim</xsl:attribute>
</xsl:template>
<!-- Change /root/person[2]/@name to "John" -->
<xsl:template match="/root/person[2]/@name">
<xsl:attribute name="name">John</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
答案 1 :(得分:1)
如果您的实施支持,请尝试XQuery Update。
replace value of node /root/person[1]/@name with "Jim",
replace value of node /root/person[2]/@name with "John"
答案 2 :(得分:0)
element root {
for $person at $i in doc('Sample.xml')/root/person
let $new-name := if($i eq 1) then "Jim" else "John"
return
element person {
attribute name { $new-name },
$person/*
}
}