0

我有一个 XML 文件,想将其显示为 XML 而不是字符串,但我不能使用 JAXB 解组器,因为我没有仅从一个类结构创建它,我为主体创建了一个类和一个用于保存的类对象以获取此 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);

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

4

1 回答 1

0

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

代码取自此处,未经测试。这个想法应该很清楚。

    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.");
    }
于 2013-06-05T14:28:37.227 回答