我想更改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>
对XML文档进行小的更改在XSLT:中最容易实现
<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>
如果您的实现支持XQuery更新,请尝试它。
replace value of node /root/person[1]/@name with "Jim",
replace value of node /root/person[2]/@name with "John"
hmm也许只是重建它并在FLOWR中进行更改?-->
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/*
}
}