有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在第二行的现有xml文件中添加xmlstylesheet

我有一个xml字符串文件,我想在xml字符串文件的第二行添加xml样式表。 但下面给出的代码给出了如下输出: 首先是xml-string文件,然后在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=\"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;
}
}

共 (1) 个答案

  1. # 1 楼答案

    语句Element root = doc.createElement("root-element");创建了一个名为root-element的新元素,当您调用doc.appendChild(root);时,实际上是将它附加到文档的末尾。在这两条语句之后,您的文档将是这样的:

    <?xml version="1.0" encoding="UTF-8"?>
    <Emp id="1">
        <name>Pankaj</name>
        <age>25</age>
        <role>Developer</role>
        <gen>Male</gen>
    </Emp>
    <root-element/>
    

    然后是doc.insertBefore((Node) pi, root);,这导致在这个新添加的元素之前添加样式表处理指令

    要解决这个问题,您必须检索一个指向文档根元素的指针(而不是添加一个名为root-element的新元素),然后在它前面添加pi。这可以通过调用doc对象的getDocumentElement()方法来实现。因此,为了解决这个问题,您只需要在main方法中使用以下代码:

    Element root = doc.getDocumentElement();
    doc.insertBefore((Node) pi, root);