私の人生にとって、なぜこのことが自分のコードで起こっているのか分かりません。メソッド名を変更すると不要なXMLブロックが追加される
私は、既存のXMLファイルにXMLブロックを追加するJavaプログラムを作成しました。例:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<bookList>
<book>
<author>Neil Strauss</author>
<bookName>The Game</bookName>
</book>
</bookList>
ここで、bookListにブックを追加します。だから私は、Unmarshallerのを作成し、そのようにそれを呼び出す:これは正常に動作します
@XmlRootElement(name = "bookList")
public class Bookstore {
// XmlElement sets the name of the entities
@XmlElement(name = "book")
private ArrayList<Book> bookList;
public void setBookList(ArrayList<Book> bookList) {
this.bookList = bookList;
}
public ArrayList<Book> getBooksList() {
return bookList;
}
}
:
BookMain.java:
ArrayList<Book> bookList = new ArrayList<Book>();
JAXBContext context = JAXBContext.newInstance(Bookstore.class);
Unmarshaller um = context.createUnmarshaller();
Bookstore bookstore2 = (Bookstore) um.unmarshal(new FileReader(
"./bookstore.xml"));
Book book3 = new Book();
book3.setName("Test");
book3.setAuthor("TestAuthor");
bookstore2.getBooksList().add(book3);
Marshaller map = context.createMarshaller();
map.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
map.marshal(bookstore2, System.out);
Bookstore.javaを。それは問題なしで本の中に本を追加します。しかし、その後、私はsetBListとgetBListに二つの方法、setBookListとgetBookListを変更すると、突然、出力は次のようになります。
<bookList>
<book>
<author>Neil Strauss</author>
<bookName>The Game</bookName>
</book>
<book>
<author>TestAuthor</author>
<bookName>Test</bookName>
</book>
<BList>
<author>Neil Strauss</author>
<bookName>The Game</bookName>
</BList>
<BList>
<author>TestAuthor</author>
<bookName>Test</bookName>
</BList>
</bookList>
なぜXMLのこれらの不要なブロックを追加メソッド名を変更し、どのように私はそれを修正するだろう私はこのメソッド名を不要な結果なしに変更できますか?
@XmlRootElement(name = "book")
// If you want you can define the order in which the fields are written
// Optional
@XmlType(propOrder = { "author", "name" })
public class Book {
private String name;
private String author;
// If you like the variable name, e.g. "name", you can easily change this
// name for your XML-Output:
@XmlElement(name = "bookName")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
あなたは 'Book.java'を提供できますか? – Thor
私は自分の回答を編集し、あなたが要求したとおりに追加しました。 – Otra
出力を確認できます。興味深い質問! – Thor