gpt4 book ai didi

java - 在 xml 字符串的第二行添加 xml-stylesheet

转载 作者:太空宇宙 更新时间:2023-11-04 07:21:37 24 4
gpt4 key购买 nike

如何在xml文件的第二行添加样式表,我已经编写了代码,但它在我的xml字符串文件的第一行添加了样式表,请参阅我的代码,它是工作代码,但它在xml字符串的第一行添加样式表,我的要求是在xml字符串的第二行添加xml样式表,请帮助

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=\"cda.xsl\"");
Element root = doc.getDocumentElement();
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;
}
}

最佳答案

改造前

transformer.transform(new DOMSource(doc), new StreamResult(writer));

尝试使用以下输出属性,

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");

关于java - 在 xml 字符串的第二行添加 xml-stylesheet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19240770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com