如何在不设置新实例类的情况下将XML文件显示为XML数据?

时间:2013-06-05 14:08:09

标签: java xml jaxb marshalling unmarshalling

我有一个XML文件,并希望将其显示为XML而不是String但我不能使用JAXB unmarshaller,因为我没有从一个类结构创建它,我为一个类和一个类创建了一个类保持对象以获取此XML表单:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<XmlSource>
<XmlConf>
    <hostName>weather.yahooapis.com</hostName>
    <parameters>
        <entry>
            <key>w</key>
            <value>2502265</value>
        </entry>
    </parameters>
    <URLPath>/forecastrss</URLPath>
    <urlProtocol>http</urlProtocol>
</XmlConf>
<XmlConf>
    <hostName>weather.yahooapis.com</hostName>
    <parameters>
        <entry>
            <key>w</key>
            <value>2502265</value>
        </entry>
    </parameters>
    <URLPath>/forecastrss</URLPath>
    <urlProtocol>http</urlProtocol>
</XmlConf>
<XmlConf>
    <hostName>weather.yahooapis.com</hostName>
    <parameters>
        <entry>
            <key>w</key>
            <value>2502265</value>
        </entry>
    </parameters>
    <URLPath>/forecastrss</URLPath>
    <urlProtocol>http</urlProtocol>
</XmlConf>
</XmlSource>

所以,我使用了以下编组方法:

public void add(String fileName) throws IOException, JAXBException,
            ParserConfigurationException, SAXException, TransformerException {

                XmlConf object;
        this.fileName = fileName; 
        File temp = new File(tempName);
        JAXBContext jaxbContext = JAXBContext.newInstance(XmlConfList.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        File source = new File(fileName);
        if (source.exists()) {

            jaxbMarshaller.marshal(object, temp);
            MergeXml merge = new MergeXml();
            merge.mergeXML(true, fileName, tempName, mainTag);
        } else {
            XmlStructure struct = new XmlStructure();
            jaxbMarshaller.marshal(struct, source);
            jaxbMarshaller.marshal(object, temp);
            MergeXml merge = new MergeXml();
            merge.mergeXML(true, fileName, tempName, mainTag);
        }
        temp.delete();
    }

并使用此类合并两个XML结构:

public class MergeXml {

    private static final String YES = "yes";
    private static final String generalTag = "*";

    /**
     * This method used to merge XML old and new files together
     * 
     * @param condition
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     * @throws TransformerException
     */
    public void mergeXML(boolean condition, String fileName, String tempName, String mainTag)
            throws ParserConfigurationException, SAXException, IOException,
            TransformerException {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = null;
        Document doc = null;
        Document doc2 = null;

        db = dbf.newDocumentBuilder();
        doc = db.parse(new File(fileName));
        doc2 = db.parse(new File(tempName));

        NodeList elements = doc.getElementsByTagName(mainTag);

        if (condition == true) {
            NodeList nodeList = doc2.getElementsByTagName(generalTag);

            for (int i = 0; i < nodeList.getLength(); i++) {

                Node node = nodeList.item(i);
                Node childNode = doc.adoptNode(node);

                elements.item(0).appendChild(childNode);
            }

        }

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, YES);

        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new StringWriter());
        transformer.transform(source, result);

        BufferedWriter output = new BufferedWriter(new FileWriter(fileName));
        String xmlOutput = result.getWriter().toString();
        output.write(xmlOutput);
        output.close();

    }
}

那么,我该如何解组?我不能写:

JAXBContext jaxbContext = JAXBContext.newInstance(something.class);

因为它在我的情况下不起作用。

1 个答案:

答案 0 :(得分:0)

我建议您使用DOM Level 3 Load and Save (LS) API:org.w3c.dom.ls.LSSerializer

代码取自here而未经过测试。这个想法应该是清楚的。

    DOMImplementation domImplementation = document.getImplementation();
    if (domImplementation.hasFeature("LS", "3.0")
            && domImplementation.hasFeature("Core", "2.0")) {
        DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementation
                .getFeature("LS", "3.0");
        LSSerializer lsSerializer = domImplementationLS
                .createLSSerializer();
        DOMConfiguration domConfiguration = lsSerializer.getDomConfig();
        if (domConfiguration.canSetParameter("format-pretty-print",
                Boolean.TRUE)) {
            lsSerializer.getDomConfig().setParameter("format-pretty-print",
                    Boolean.TRUE);
            LSOutput lsOutput = domImplementationLS.createLSOutput();
            lsOutput.setEncoding("UTF-8");
            StringWriter stringWriter = new StringWriter();
            lsOutput.setCharacterStream(stringWriter);
            lsSerializer.write(document, lsOutput);
            return stringWriter.toString();
        } else {
            throw new RuntimeException(
                    "DOMConfiguration 'format-pretty-print' parameter isn't settable.");
        }
    } else {
        throw new RuntimeException(
                "DOM 3.0 LS and/or DOM 2.0 Core not supported.");
    }