廣告聯播

2018年12月7日 星期五

[Solved] DocumentBuilder parse XML returns null <解決 org.w3c.dom.Document 解析 XML 檔回傳值均為 NULL>

From: Polin Wei Document 解析 XML 檔案時, 解析的值總是為 NULL , 解決方法如下: 先把檔案用 StringBuilder 變成字串後, 再作解析就可以
import org.springframework.util.ResourceUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class TestFunc {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
try {
File xmlFile = ResourceUtils.getFile("classpath:ckfinder-config.xml");
readMXLFile(xmlFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void readMXLFile(File xmlFile) throws Exception {
InputStream is = new FileInputStream(xmlFile);
StringBuilder contentBuilder = new StringBuilder();
try (Stream stream = Files.lines(Paths.get(xmlFile.getAbsolutePath()), StandardCharsets.UTF_8)) {
stream.forEach(s -> contentBuilder.append(s).append("\n"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(contentBuilder.toString());
ByteArrayInputStream bis = new ByteArrayInputStream(contentBuilder.toString().getBytes());
繼續閱讀

沒有留言:

張貼留言