gpt4 book ai didi

java - 更改方法名称会添加不需要的 XML block

转载 作者:行者123 更新时间:2023-11-30 09:48:10 25 4
gpt4 key购买 nike

对于我的生活,我无法弄清楚为什么我的代码会发生这种情况。

我编写了一个 Java 程序来将 XML block 添加到现有的 XML 文件中。举例说明:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<bookList>
<book>
<author>Neil Strauss</author>
<bookName>The Game</bookName>
</book>
</bookList>

现在,我想在 bookList 中添加一本书。所以我创建了一个 Unmarshaller 并这样调用它:

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);

书店.java:

@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;
}
}

这很好用。它在书单中添加一本书没问题。但是后来我将 setBookList 和 getBookList 这两个方法更改为 setBList 和 getBList,突然,输出如下所示:

<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 block ,我该如何修复它才能更改此方法名称而不会产生不良后果?

编辑这里是请求的Book.java

@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;
}

}

最佳答案

JAXB 默认为@XmlAcessorType(XmlAcessType.PUBLIC)。这意味着它将映射所有公共(public)访问器/字段以及带注释的字段。当字段名称与访问器匹配时,JAXB 会识别出它们是相关的。当您更改名称时,它没有。要解决此问题,您可以注释访问器或使用 XmlAccesssType.FIELD。

关于java - 更改方法名称会添加不需要的 XML block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6376851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com