[英]Remove data from XML file in DOM?
有没有一种简单的方法(可能使用 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,您必须自己在结构中进行迭代,而是查看 SAX API,它会自行迭代并为每个元素、文本节点等回叫您。对于每个元素,您都会被回叫因为,你也会得到一组属性。
您仍然需要确定 output 的内容,减少重复项等。但是您也会收到一个元素结束的回调,所以也许记录你得到的所有内容,然后记录你的元素结束回调,只是确定您希望 output 的唯一数据集。
有很多可能性:
我认为 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.