2017-08-07 97 views
2

我使用Java和XSL樣式表從XML文件檢索值並將其輸出到文本文件。javax.xml.transform.Source的字符串操作

下面是所使用的程序:

TransformerFactory factory = TransformerFactory.newInstance(); 
    Source xslt = new StreamSource(new File("transform.xsl")); 
    Transformer transformer = factory.newTransformer(xslt); 
    Source text = new StreamSource(new File("inputXML.txt"));   
    transformer.transform(text, new StreamResult(new File("output.txt"))) ; 

但最近我發現XML文件,我會閱讀將有2個節點,而不是一個。所以我想這樣做的字符串操作來添加自己的根節點編程,使我能避免以下錯誤:

ERROR: 'The markup in the document following the root element must be well-formed.' ERROR: 'com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: The markup in the document following the root element must be well-formed.'

不過,我不能做任何字符串操作對javax.xml.transform.Source (鑄造不工作)。 我不想使用中間文件來添加我的根節點,因爲我擔心它會證明代價高昂,因爲我需要處理接近50k的XML記錄。

回答

0

StreamSource有幾個構造函數

Path inputPath = Paths.get("inputXML.txt"); 
String input = new String(Files.readAllBytes(inputPath, 
        StandardCharsets.UTF_8)); 
input = input.replaceFirst("<quasiroot", "<root>$0") 
    + "</root>"; 

Source text = new StreamSource(new StringReader(input));   
+0

我對如何處理「輸入」以實現結果略有差異。謝謝 。非常感激 –

0

注意,在Java世界中,你有XML解析器喜歡與external entities支持的Xerces,所以你可以簡單地構建一個文件例如引用您的其他文件

<!DOCTYPE root [ 
    <!ENTITY input SYSTEM "inputXML.txt"> 
]> 
<root>&input;</root> 

然後您需要做的就是加載該文件作爲XSLT的源文件。不需要字符串操作,至少不需要操縱整個XML,如果你願意,你可以直接將上面的字符串構造成一個字符串,然後通過StringReader將它傳遞給一個StreamSource,在這裏你將系統ID設置爲你的目錄輸入XML:

String input = "inputXML.txt"; 
    File dir = new File("."); 
    String baseUri = dir.toURI().toASCIIString(); 
    String inputXml = "<!DOCTYPE root [ <!ENTITY input SYSTEM \"" + input + "\">]><root>&input;</root>"; 
    TransformerFactory factory = TransformerFactory.newInstance(); 
    Source xslt = new StreamSource(new File("transform.xsl")); 
    Transformer transformer = factory.newTransformer(xslt); 
    Source text = new StreamSource(new StringReader(inputXml), baseUri); 
    transformer.transform(text, new StreamResult(new File("output.txt")));