コメントすると、削除するノードにIdentity Transformと空のテンプレートを実行するXSLTを考えてみましょう。論理、またはこの解決策に必要なデータ構造(例えば、arraylist、ハッシュマップ)の使用を含むことができる。
情報として、XSLTは、xmlファイルを他のxml、html、さらにはテキストファイル(csv/txt)に変換するように設計された特殊目的言語(XPathの兄弟)です。 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のサポートがあり、必要な変換は非常に簡単です。 –