이 자습서 에서 xml 데이터를 구문 분석하려고합니다 . 하지만 계속 오류가 발생합니다.
Exception in thread "main" org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 40; Premature end of file.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at convert.ExcelXmlReader.getAndParseFile(ExcelXmlReader.java:60)
at convert.ExcelXmlReader.main(ExcelXmlReader.java:32)
파일을 다운로드 할 수 있으며, XML 형식을 지정할 수 있도록 그의 코드를 편집했습니다. 내 최종 게임은 이것을 Access로 가져 오는 것이지만 구문 분석하는 데 문제가 있습니다.
또한 코드에서 exml 버전 및 인코딩에 대해 무언가를 사용했지만 내 xml 파일에 이미 ()가 있으므로 제거했습니다. 내가 뭘해야할지 모르겠어요.
private static void getAndParseFile() throws Exception {
System.out.println("getAndParseFile");
String fileName="C:\\Users\\windowsUserName\\Downloads\\F7BAH1P2_List.xml";
File file = new File(fileName);
removeLineFromFile(file.getAbsolutePath());
System.out.println("Finished Removing Lines");
String fileContent = IOUtils.toString(new FileInputStream(file));
SAXParserFactory parserFactor = SAXParserFactory.newInstance();
SAXParser parser = parserFactor.newSAXParser();
SAXHandler handler = new SAXHandler();
ByteArrayInputStream bis = new ByteArrayInputStream(fileContent.getBytes());
parser.parse(bis, handler); \\Apparently error happens here**
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet();
//Converts all rows to POI rows
int rowCount = 0;
for (XmlRow subsRow : handler.xmlRowList) {
Row row = sheet.createRow(rowCount);
int cellCount = 0;
for (String cellValue : subsRow.cellList) {
Cell cell = row.createCell(cellCount);
cell.setCellValue(cellValue);
cellCount++;
}
rowCount++;
}
String fileOutPath = "C:\\Users\\windowsUserName\\Downloads\\fileOut.xls";
FileOutputStream fout = new FileOutputStream(fileOutPath);
workbook.write(fout);
workbook.close();
fout.close();
if (file.exists()) {
System.out.println("delete file-> " + file.getAbsolutePath());
if (!file.delete()) {
System.out.println("file '" + file.getAbsolutePath() + "' was not deleted!");
}
}
System.out.println("getAndParseFile finished, processed " + " substances!");
}
내가 편집하는 방법을 모르지만 그것이 옳다고 생각하는 그들의 SaxHandler.java 파일? 내 xml 파일에도 "행"과 "데이터"가 모두 표시됩니다.
package convert;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
import java.util.List;
class SAXHandler extends DefaultHandler {
List<XmlRow> xmlRowList = new ArrayList<>();
XmlRow xmlRow = null;
String content = null;
@Override
//Finds start of Row
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("row"))
xmlRow = new XmlRow();
}
@Override
//Finds end of Row tag
public void endElement(String uri, String localName, String qName) throws SAXException {
switch (qName) {
case "Row": //if it's the </row>,
xmlRowList.add(xmlRow); //add this row in the rowlist?
break;
case "Data": //if it is </data>
xmlRow.cellList.add(content); //
break;
}
}
@Override
//Gets data between the tags.
public void characters(char[] ch, int start, int length) throws SAXException {
content = String.copyValueOf(ch, start, length).trim();
}
}
Excel / Xml 파일 :
<?xml version="1.0" encoding="utf-16"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
<Author>marc</Author>
<LastAuthor>ESDI</LastAuthor>
</DocumentProperties>
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
<WindowHeight>7560</WindowHeight>
<WindowWidth>12300</WindowWidth>
<WindowTopX>360</WindowTopX>
<WindowTopY>135</WindowTopY>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
<Styles>
<Style ss:ID="Default" ss:Name="Normal">
<Alignment ss:Vertical="Bottom"/>
<Borders/>
<Font/>
<Interior/>
<NumberFormat/>
<Protection/>
</Style>
<Style ss:ID="s21">
<NumberFormat ss:Format="Short Date"/>
</Style>
</Styles>
<Worksheet ss:Name="Sheet1">
<Table x:FullColumns="1" x:FullRows="1">
<Row>
<Cell><Data ss:Type="String">Crt. Dte</Data></Cell>
<Cell><Data ss:Type="String">WR Status</Data></Cell>
<Cell><Data ss:Type="String">Request Plant</Data></Cell>
<Cell><Data ss:Type="String">Request #</Data></Cell>
<Cell><Data ss:Type="String">Item#</Data></Cell>
<Cell><Data ss:Type="String">Request Cost Center</Data></Cell>
<Cell><Data ss:Type="String">WR Description</Data></Cell>
<Cell><Data ss:Type="String">W/O No</Data></Cell>
<Cell><Data ss:Type="String">Charge Plant</Data></Cell>
<Cell><Data ss:Type="String">Charge Cost Center</Data></Cell>
<Cell><Data ss:Type="String">Equip NO</Data></Cell>
<Cell><Data ss:Type="String">Equipment Name</Data></Cell>
<Cell><Data ss:Type="String">Required Date</Data></Cell>
<Cell><Data ss:Type="String">WO Type</Data></Cell>
<Cell><Data ss:Type="String">Exec. C/C</Data></Cell>
<Cell><Data ss:Type="String">Exec. Plant</Data></Cell>
<Cell><Data ss:Type="String">Plant1</Data></Cell>
<Cell><Data ss:Type="String">Area</Data></Cell>
<Cell><Data ss:Type="String">Confirmed</Data></Cell>
<Cell><Data ss:Type="String">WO Status</Data></Cell>
<Cell><Data ss:Type="String">W/R Requester</Data></Cell>
</Row>
</Table>
<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
<Selected/>
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</Worksheet>
</Workbook>
나는 다른 답변을보고 있었지만 모두이 오류가 xml 파일에 부분 앞에 무언가가있을 때만 발생한다고 말합니다. 그러나 거기에는 아무것도 없습니다. 그 외에는 공백 (탭 항목)을 제거했는데 오류가 계속 발생합니다.
RemoveLineFromFile은 자습서에서 수정되었습니다. 그러나 기본적으로 시작과 끝에 데이터가 포함되지 않은 원래 빈 행 (처음에 2 개, 끝에 2 개)을 제거합니다. 제거되었는지 확인합니다.
private static void removeLineFromFile(String file) {
BufferedReader br = null;
PrintWriter pw = null;
try {
File inFile = new File(file);
if (!inFile.isFile()) {
return;
}
br = new BufferedReader(new FileReader(file));
String line = null;
int totalRows=0;
boolean continueMethod = false;
//Count total number of rows in file
while ((line = br.readLine()) != null) {
//check if file is already formatted
if (line.contains("List for Work")){
continueMethod = true;
}
if (line.toLowerCase().contains("</row>")){
++totalRows;
}
}
if (continueMethod)
{
//Create a temporary file to hold the file with deleted lines.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
pw = new PrintWriter(new FileWriter(tempFile));
line = null;
br.close();
br = null;
br = new BufferedReader(new FileReader(file));
boolean ignoreMe = false;
int rowCounter = 0;
int rowCloser = 0;
//begin cycling through file and writing to new one.
while((line = br.readLine()) != null)
{
//if runs into a row, count it.
if (line.toLowerCase().contains("<row>")){
rowCounter++;
}
if (line.toLowerCase().contains("</row>")){
rowCloser++;
}
//Delete the first two, and last two lines
if ((rowCounter == 1 ) || (rowCounter == 2) || (rowCounter == (totalRows-1)) || (rowCounter == totalRows))
{
ignoreMe = true;
//If it reached the last closing tag, exit out of this to allow it to write the rest of the file.
if (rowCloser==totalRows)
rowCounter++;
}
else
{
ignoreMe = false;
}
//copy over other lines
if (!ignoreMe)
{
pw.println(line);
pw.flush();
}
}
br.close();
pw.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete original file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename temp file");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
RemoveLineFromFile을 사용하기 전에 xmlfile :
<?xml version="1.0" encoding="utf-16"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office">
<Author>marc</Author>
<LastAuthor>ESDI</LastAuthor>
</DocumentProperties>
<ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
<WindowHeight>7560</WindowHeight>
<WindowWidth>12300</WindowWidth>
<WindowTopX>360</WindowTopX>
<WindowTopY>135</WindowTopY>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
<Styles>
<Style ss:ID="Default" ss:Name="Normal">
<Alignment ss:Vertical="Bottom"/>
<Borders/>
<Font/>
<Interior/>
<NumberFormat/>
<Protection/>
</Style>
<Style ss:ID="s21">
<NumberFormat ss:Format="Short Date"/>
</Style>
</Styles>
<Worksheet ss:Name="Sheet1">
<Table x:FullColumns="1" x:FullRows="1">
<Row>
<Cell><Data ss:Type="String">List for Work Request(F7BAH1P)</Data></Cell>
</Row>
<Row>
</Row>
<Row>
<Cell><Data ss:Type="String">Crt. Dte</Data></Cell>
<Cell><Data ss:Type="String">WR Status</Data></Cell>
<Cell><Data ss:Type="String">Request Plant</Data></Cell>
<Cell><Data ss:Type="String">Request #</Data></Cell>
<Cell><Data ss:Type="String">Item#</Data></Cell>
<Cell><Data ss:Type="String">Request Cost Center</Data></Cell>
<Cell><Data ss:Type="String">WR Description</Data></Cell>
<Cell><Data ss:Type="String">W/O No</Data></Cell>
<Cell><Data ss:Type="String">Charge Plant</Data></Cell>
<Cell><Data ss:Type="String">Charge Cost Center</Data></Cell>
<Cell><Data ss:Type="String">Equip NO</Data></Cell>
<Cell><Data ss:Type="String">Equipment Name</Data></Cell>
<Cell><Data ss:Type="String">Required Date</Data></Cell>
<Cell><Data ss:Type="String">WO Type</Data></Cell>
<Cell><Data ss:Type="String">Exec. C/C</Data></Cell>
<Cell><Data ss:Type="String">Exec. Plant</Data></Cell>
<Cell><Data ss:Type="String">Plant1</Data></Cell>
<Cell><Data ss:Type="String">Area</Data></Cell>
<Cell><Data ss:Type="String">Confirmed</Data></Cell>
<Cell><Data ss:Type="String">WO Status</Data></Cell>
<Cell><Data ss:Type="String">W/R Requester</Data></Cell>
</Row>
<Row>
</Row>
<Row>
<Cell><Data ss:Type="String">Count: 244</Data></Cell>
</Row>
</Table>
<WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
<Selected/>
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions>
</Worksheet>
</Workbook>
문자 집합 변환 문제가있는 것 같습니다.
파일을 읽기위한 코드는 다음과 같습니다.
String fileContent = IOUtils.toString(new FileInputStream(file));
// SAX parser creation omitted.
ByteArrayInputStream bis = new ByteArrayInputStream(fileContent.getBytes());
parser.parse(bis, handler); //Apparently error happens here**
기본 문자 집합을 사용하여 파일을 문자열로 읽은 다음 결과 바이트 배열 입력 스트림을 SAX 파서에 전달하기 전에 기본 문자 집합을 사용하여 다시 바이트로 변환합니다. XML 파일은 UTF-16의 문자 집합을 지정하고 기본 문자 집합이 UTF-16이 아니라고 생각하므로 다른 문자 집합을 사용하는 것처럼 UTF-16 파일을 읽는 것은 잘못된 것입니다.
에 IOUtils.toString()
및에서 호출 할 때 UTF-16 문자 집합을 지정해 볼 수 fileContent.getBytes()
있지만 솔직히 말해서 FileInputStream을 파서에 직접 전달하여 문자 집합 문제를 모두 피하는 것이 훨씬 더 간단합니다.
parser.parse(new FileInputStream(file), handler);
FileInputStream
일단 완료되면 코드 가 닫히 도록 코드를 수정해야합니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다