xml 문자열 파일의 의미있는 줄에 xml-stylesheet를 추가 할 XML 문자열 파일이 있습니다. 하지만 아래 주어진 코드는 다음과 같은 출력을 제공합니다. 먼저 xml- 문자열 파일을 만든 다음 xml 문자열 파일의 끝에 xml-stylesheet를 추가하지만 스타일 시트를 내 xml-string의 의미있는 줄에 넣고 싶습니다. 어떻게해야합니까? 덕분에 .기존 XML 파일에 xml-stylesheet를 추가했습니다.
내 코드는 다음과 같습니다
public class StringToDocumentToString {
public static void main(String[] args)
throws TransformerConfigurationException {
String xmlstring = null;
String filepath = "E:/C-CDA/MU2_CDA_WORKSPACE/AddingStylesheetTOxml/documentfile.txt";
final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"
+ "<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"
+ "<role>Developer</role><gen>Male</gen></Emp>";
Document doc2 = convertStringToDocument(xmlStr);
Document doc1 = null;
try {
doc1 = addingStylesheet(doc2);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = convertDocumentToString(doc1);
System.out.println(str);
}
private static <ProcessingInstructionImpl> Document addingStylesheet(
Document doc) throws TransformerConfigurationException,
ParserConfigurationException {
ProcessingInstructionImpl pi = (ProcessingInstructionImpl) doc
.createProcessingInstruction("xml-stylesheet",
"type=\"text/xsl\" href=\"my.stylesheet.xsl\"");
Element root = doc.createElement("root-element");
doc.appendChild(root);
doc.insertBefore((Node) pi, root);
return doc;
}
private static String convertDocumentToString(Document doc) {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer;
try {
transformer = tf.newTransformer();
// below code to remove XML declaration
// transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
// "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString();
return output;
} catch (TransformerException e) {
e.printStackTrace();
}
return null;
}
private static Document convertStringToDocument(String xmlStr) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document doc = null;
try {
builder = factory.newDocumentBuilder();
doc = builder.parse(new InputSource(new StringReader(xmlStr)));
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
}
덕분에 내 문제가 매우 solved.thank 당신입니다. –