簡體   English   中英

使用 JAXB 讀取 XML 文件

[英]read Xml file with JAXB

我想讀取一個 xml 文件(如下所示),但我得到了一個 Execption。 你能幫我解決這個問題嗎?

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation=
"file:///C:/Documents%20and%20Settings/mojalal/Desktop/FirstXSD.xml">
<log>
    <property key="firstKey" value="firstValue"></property>
    <property key="secoundKey" value="secoundKey"></property>
    <property key="thirdKey" value="thirdValue"></property>  
</log>

<env>
    <property key="firstenv" value="fo"></property>
    <property key="123" value="333"></property> 
</env>
</config>

這是我要讀取 xml 文件的代碼:

    public class ReadXMLFilewithJAXB {
private static List<Property> customer;

@SuppressWarnings("unchecked")
public static void main(String[] args) {

 try {

    File file = new File("c:\\FirstXML.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Log.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    customer = (List<Property>) jaxbUnmarshaller.unmarshal(file);
 } catch (JAXBException e) {
    e.printStackTrace();
  }

}

}

最后這是我得到的異常:

javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"config"). Expected elements are (none)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:631)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:236)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:231)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:105)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1038)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:467)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:448)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:137)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:501)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:400)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:626)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3103)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:922)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:200)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:173)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:142)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:151)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:169)
    at firstExample.ReadXMLFilewithJAXB.main(ReadXMLFilewithJAXB.java:21)

環境 POJO 類:

public class Env {
    List<Property> properties2;


    public Env() {
    }


    public Env(List<Property> properties2) {
        super();
        this.properties2 = properties2;
    }


    public List<Property> getProperties2() {
        return properties2;
    }

    public void setProperties2(List<Property> properties2) {
        this.properties2 = properties2;
    }

日志 POJO 類:

@XmlRootElement
public class Log {
    List<Property> properties=new ArrayList<Property>();;

    public Log(){

    }

    public List<Property> getProperties() {
        return properties;
    }

    public void setProperties(List<Property> properties) {
        this.properties = properties;
    }
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"config"). Expected elements are (none)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:631)

您需要確保使用@XmlRootElement@XmlElementDecl將類與 XML 文檔的根元素相關聯(請參閱: http : @XmlRootElement ) . 或者,您可以使用采用Class參數的解組方法之一來告訴 JAXB 您要解組的對象類型。


領域模型(配置)

我建議使用如下所示的域類,您可以從中獲取兩個Property對象列表。

import java.util.*;
import javax.xml.bind.annotation.*;

@XmlRootElement
public class Config {

    private List<Property> logProperties = new ArrayList<Property>();
    private List<Property> envProperties = new ArrayList<Property>();

    @XmlElementWrapper(name="log")
    @XmlElement(name="property")
    public List<Property> getLogProperties() {
        return logProperties;
    }

    @XmlElementWrapper(name="env")
    @XmlElement(name="property")
    public List<Property> getEnvProperties() {
        return envProperties;
    }

}

演示

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Config.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum17059227/input.xml");
        Config config = (Config) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "file:///C:/Documents%20and%20Settings/mojalal/Desktop/FirstXSD.xml");
        marshaller.marshal(config, System.out);
    }

}

輸入.xml/輸出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file:///C:/Documents%20and%20Settings/mojalal/Desktop/FirstXSD.xml">
    <env>
        <property key="firstenv" value="fo"/>
        <property key="123" value="333"/>
    </env>
    <log>
        <property key="firstKey" value="firstValue"/>
        <property key="secoundKey" value="secoundKey"/>
        <property key="thirdKey" value="thirdValue"/>
    </log>
</config>

當您描述一個 XML 模型時,您需要從一個根實體開始(在您的例子中它是<config>元素)。

@XmlRootElement(name="config")
class Config implements Serializable {
   private Log log;
   private Env env;

   @XmlElement(name="log")
   public Log getLog() {
      return this.log;
   }

   @XmlElement(name="env")
   public Env getEnv() {
      return this.env;
   }

   // Setters are omitted
}

然后像下面這樣解析 XML:

JAXBContext jaxbContext = JAXBContext.newInstance(Config.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Config config = (Config) jaxbUnmarshaller.unmarshal(file);
if (config != null && config.getLog() != null) {
   customer = config.getLog().getProperties();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM