gpt4 book ai didi

java - 从 DOM 中的 XML 文件中删除数据?

转载 作者:数据小太阳 更新时间:2023-10-29 02:37:26 26 4
gpt4 key购买 nike

有没有一种简单的方法(可能使用 DOM api 或其他方法)我可以从 XML 文件中删除实际数据,只留下一种模式模板,以便我们可以看到它的潜在信息可以坚持。

我将举个例子来说明这一点。

考虑用户输入以下 xml 文件:

<photos page="2" pages="89" perpage="10" total="881">
<photo id="2636" owner="47058503995@N01"
secret="a123456" server="2" title="test_04"
ispublic="1" isfriend="0" isfamily="0" />
<photo id="2635" owner="47058503995@N01"
secret="b123456" server="2" title="test_03"
ispublic="0" isfriend="1" isfamily="1" />
<photo id="2633" owner="47058503995@N01"
secret="c123456" server="2" title="test_01"
ispublic="1" isfriend="0" isfamily="0" />
<photo id="2610" owner="12037949754@N01"
secret="d123456" server="2" title="00_tall"
ispublic="1" isfriend="0" isfamily="0" />
</photos>

然后我想把它变成:

<photos page=“..." pages=“..." perpage=“..." total=“...">
<photo id=“.." owner=“.."
secret=“..." server=“..." title=“..."
ispublic=“..." isfriend=“..." isfamily=“...” />
</photos>

我确信这可以手动编写,但这是最好、最有效和最可靠的方式。 (最好使用 Java)。

谢谢!

最佳答案

有很多可能性:

  • DOM API(包含在 JDK 中)
  • SAX API(包含在 JDK 中)
  • JDOM(易于使用,但外部)
  • XSLT(使用准备好的 XSL 样式表转换 XML,JDK 支持 XSLT 1.0)

我认为 XSLT 是将 XML 转换为另一种 XML 的最可靠和通用的方法。这是一些简单的例子:

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

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

<xsl:template match="@*">
<xsl:attribute name="{name()}">...</xsl:attribute>
</xsl:template>
</xsl:stylesheet>

结果:

<photos page="..." pages="..." perpage="..." total="...">
<photo id="..." owner="..." secret="..." server="..." title="..." ispublic="..."
isfriend="..."
isfamily="..."/>
</photos>

关于java - 从 DOM 中的 XML 文件中删除数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6718231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com