[英]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.