如上所述,請考慮運行Identity Transform的XSLT以及要刪除的節點上的空模板。否for
循環,if
邏輯,或使用此解決方案所需的數據結構(例如,數組列表,hashmaps)。
作爲信息,XSLT是一種專用語言(與XPath同級),旨在將xml文件轉換爲其他xml,html甚至文本文件(csv/txt)。諸如Java,PHP,Python和其他語言的通用語言使庫運行XSLT 1.0腳本,甚至可以調用像libxslt/Saxon這樣的外部專用XSLT處理器。另外,XSLT腳本本身也是格式良好的XML文件,可以根據任何動態需求從文件或字符串進行解析。
XSLT(另存爲的.xsl腳本從文件中下面的Java解析)
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output version="1.0" encoding="UTF-8" indent="yes" />
<xsl:strip-space elements="*"/>
<!-- Identity Transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- Removes all price tags -->
<xsl:template match="price"/>
</xsl:transform>
的Java
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.OutputKeys;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class CourseList {
public static void main(String[] args) throws IOException, URISyntaxException,
SAXException,
ParserConfigurationException,
TransformerException {
// LOAD XML AND XSL DOCUMENTS
String inputXML = "C:\\Path\\To\\Input.xml";
String xslFile = "C:\\Path\\To\\XSLTScript.xsl";
String outputXML = "C:\\Path\\To\\Output.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File(inputXML));
Source xslt = new StreamSource(new File(xslFile));
// XSLT TRANSFORMATION WITH PRETTY PRINT
TransformerFactory prettyPrint = TransformerFactory.newInstance();
Transformer transformer = prettyPrint.newTransformer(xslt);
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(outputXML));
transformer.transform(source, result);
}
}
寫自己的解析器,爲此目的將需要大約最多10分鐘 –
您想使用哪種模式? DOM,OM,JAXB還是自定義分析器? –
我不建議爲XML編寫自己的解析器,因爲它比你想象的更復雜。但是,如果您真的處理嚴格限制的XML配置文件,那麼這樣做可能有意義。我自己,我傾向於用XSLT轉換做這種工作。 Java支持XSLT,所需的轉換將非常簡單。 –