英文:
Append or replace XML element based on attribute value using java
问题
我有两个具有相似结构的 XML 文件,我希望根据其属性 Id 的值将它们合并为一个文件。如果 Id 值已经存在,代码应该替换其他属性,否则只是追加一个元素。您可以建议我使用哪个 Java XML 解析库吗?
因此,我将非常感谢任何给我任何示例的人。提前谢谢。
XML A:
<Returns>
<Return Id="1001" MetadataFields="Code" MandatoryFields="Code1"/>
</Returns>
XML B:
<Returns>
<Return Id="1000" MetadataFields="BankCode" MandatoryFields="BankCode"/>
<Return Id="1001" MetadataFields="BankCode" MandatoryFields="BankCode1"/>
<Return Id="1002" MetadataFields="BankCode" MandatoryFields="BankCode2"/>
<Return Id="1003" MetadataFields="BankCode" MandatoryFields="BankCode3"/>
</Returns>
输出:
<Returns>
<Return Id="1000" MetadataFields="BankCode" MandatoryFields="BankCode"/>
<Return Id="1001" MetadataFields="Code" MandatoryFields="Code1"/>
<Return Id="1002" MetadataFields="BankCode" MandatoryFields="BankCode2"/>
<Return Id="1003" MetadataFields="BankCode" MandatoryFields="BankCode3"/>
</Returns>
英文:
I have two XML files of similar structure which I wish to merge into one file based on its attribute Id value. if Id value already exists, the code should replace other attributes else just append an element. Can you suggest which java XML parser library I can use?
So I would be grateful to anyone who gives me any sample example. Thanks in advance.
XML A:
<Returns>
<Return Id="1001" MetadataFields="Code" MandatoryFields="Code1"/>
</Returns>
XML B:
<Returns>
<Return Id="1000" MetadataFields="BankCode" MandatoryFields="BankCode"/>
<Return Id="1001" MetadataFields="BankCode" MandatoryFields="BankCode1"/>
<Return Id="1002" MetadataFields="BankCode" MandatoryFields="BankCode2"/>
<Return Id="1003" MetadataFields="BankCode" MandatoryFields="BankCode3"/>
</Returns>
Output:
<Returns>
<Return Id="1000" MetadataFields="BankCode" MandatoryFields="BankCode"/>
<Return Id="1001" MetadataFields="Code" MandatoryFields="Code1"/>
<Return Id="1002" MetadataFields="BankCode" MandatoryFields="BankCode2"/>
<Return Id="1003" MetadataFields="BankCode" MandatoryFields="BankCode3"/>
</Returns>
答案1
得分: 1
在XSLT 3.0中:
<xsl:template name="xsl:initial-template">
<Records>
<xsl:merge>
<xsl:merge-source for-each-source="doc('A.xml'), doc('B.xml')"
streamable="yes"
select="Returns/Return">
<xsl:merge-key select="@Id" order="ascending"/>
</xsl:merge-source>
<xsl:merge-action>
<xsl:copy-of select="current-merge-group()[last()]"/>
</xsl:merge-action>
</xsl:merge>
</Records>
</xsl:template>
英文:
In XSLT 3.0:
<xsl:template name="xsl:initial-template">
<Records>
<xsl:merge>
<xsl:merge-source for-each-source="doc('A.xml'), doc('B.xml')"
streamable="yes"
select="Returns/Return">
<xsl:merge-key select="@Id" order="ascending"/>
</xsl:merge-source>
<xsl:merge-action>
<xsl:copy-of select="current-merge-group()[last()]"/>
<xsl:merge-action>
</xsl:merge>
</Records>
</xsl:template>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论