3

xsd と xml ファイルがあります。最初に xsd ファイルから Java クラスを生成しました。その部分は完了しました。今度は xml を使用してデータをオブジェクトにフィードする必要があります。以下のコードを使用していますが、これは JAXBException をスローしています。

    try {

    File file = new File("D:\\file.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance("com.jaxb.generated");

    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Employee empObj = (Employee) jaxbUnmarshaller.unmarshal(file);
    System.out.println(empObj.getName());

  } catch (JAXBException e) {
    e.printStackTrace();
  }

そして、これが2つのクラスを含む私のxmlファイルです:

   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
     <Employee>
       <name>John</name>            
       <salary>5000</salary>
    </Employee>
    <Customer>
       <name>Smith</name>
    </Customer>

誰かが私を助けることができますか?

4

2 に答える 2

3

重要

コードにエラーがあります。このステップをスキップしました:

JAXBElement element = (JAXBElement) jaxbUnmarshaller.unmarshal(f);


ええと、私はずっと前にJAXBと仕事をしました。

ただし、このような状況で使用したのは、他の要素を囲む最上位の要素(Javaコードまたはxsdファイル)を定義することでした。

例えば:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<People>
   <Employee>
      <name>John</name>            
      <salary>5000</salary>
      </Employee>
    <Customer>
      <name>Smith</name>
    </Customer>
</People>

Javaは、Peopleの子としてクラスEmployeeとCustomerを生成します。

次の方法で、JAXBコードで反復処理できます。

try {
   File file = new File("D:\\file.xml");
   JAXBContext jaxbContext = JAXBContext.newInstance("com.jaxb.generated");

   Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
   JAXBElement element = (JAXBElement) jaxbUnmarshaller.unmarshal(file);
   People people = (People) element.getValue();
   Employee employee = (Employee)people.getChildren().get(0); // the name of the getChildren() methodm may vary
   Customer customer = (Customer)people.getChildren().get(1);
   System.out.println(empObj.getName());
} catch (JAXBException e) {
   e.printStackTrace();
}

また、この同様の質問を確認することもできます:iterate-through-the-elements-in-jaxb

于 2012-06-23T06:56:01.660 に答える
3

質問の XML ドキュメントは無効です。XML ドキュメントには、単一のルート要素が必要です。最初のステップは、クラスを生成した XML スキーマに対して XML ドキュメントが有効であることを確認することです。

于 2012-06-23T10:02:27.763 に答える