我正在尝试从控制台获取用户输入,并将其输入到XML文件中。在这个过程中,用户转到下一行,我想要接受他们输入的字符串,并创建一个新元素。以下是我正在努力实现的目标:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<note>
<header>
<Tempo Laya="2"/>
</header>
<Notes>
<n1 Bol="Text the user entered"/>
<n2 Bol="Text the user entered over the next iteration"/>
<n3 Bol="Text the user entered over the next iteration"/>
</Notes>
</note>
不过,我认为最好的方法是创建这些元素;我无法通过此创建唯一的元素名称。到目前为止,我的代码如下:
//Create note element
Element notes = doc.createElement("Notes");
rootElement.appendChild(notes);
System.out.println("Input your notes matraa by maatra. To proceed to the next maatra press ENTER. \n To exit enter END");
do{
int noteCount = 1;
System.out.println("Maatra: ");
bol = scanner.nextLine();
}while(scanner.nextLine()!= "END");
是否有任何方法可以使用上面的循环创建和附加元素。如果不是,我还能怎么做呢?
发布于 2016-02-28 07:57:07
"END"
字符串时有一个bug。您应该使用String.equals
而不是引用相等。同时,调用nextLine()
两次读取两行而不是一行。只需检查第一个读行:
while(bol.equals("END"));"END"
,内容就被编组成文档。
您可以在Oracle教程中阅读JAXB的介绍。createAttribute
的Document
中的方法createElement
)。发布于 2016-02-28 07:58:19
我建议您创建一个对象"Note“并使用JAXB。参见本教程:教程。很容易将对象转换为XML,将XML转换为对象。
https://stackoverflow.com/questions/35684673
复制