我正在尝试使用org.apache.xml.serialize.OutputFormat,org.apache.xml.serialize.XMLSerializer
格式化xml文档中的xml内容。但是我正在课堂上编译上述文件不能被保存的文件。
帮我解决问题。
import java.io.File;
import java.io.FileInputStream;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class XMLPrinter
{
public static String print(String input) throws Exception {
return print(input, null);
}
public static String print( String input , String aDocType) throws Exception
{
return print( input , aDocType, null);
}
public static String print( String input , String aDocType, String lineSeaparator) throws Exception
{
String output = "";
try
{
DocumentBuilderFactory docBuilderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder =
docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(
new InputSource( new StringReader(input)) );
StringWriter stringWriter = new StringWriter();
OutputFormat format = new OutputFormat( doc );
//NEW CODE
if(aDocType!=null)
format.setDoctype(null, aDocType);
format.setIndenting( true );
format.setLineWidth( 0 );
format.setIndent( 10 );
if(lineSeaparator != null)
format.setLineSeparator(lineSeaparator);
XMLSerializer serializer =
new XMLSerializer( stringWriter, format );
serializer.serialize(doc);
output = stringWriter.toString();
}
catch (Exception e)
{
e.printStackTrace();
//throw e;
//output = null;
throw e;
}
return output;
}
public static void main(String[] args) throws Exception
{
String XML ="";
File f = new File("E:\\interfaces\\ShipToPartyMaster100.xml");
FileInputStream fis = new FileInputStream(f);
byte[] buf = new byte[fis.available()];
fis.read(buf);
XML = new String(buf);
System.out.println(XMLPrinter.print(XML));
}
}
在导入上述文件时面对编译的地方。 为什么会这样?是因为缺少HTMLEntities.res吗?