私はgeneradetにxsdスキーマのjavaクラスをJAXB
で持っています。 Mainクラスでは、私はrecursiveNodeList(NodeList list)
というメソッドを持っています。これは単にノードリストをとり、すべての値を取得するために反復して繰り返します。JAXB:値を設定しただけで値が返され、他の値を設定すると実際の値が返されるのはなぜですか?
私は単純に理解できないもの以外はすべて動作します。 I以下のコードで
は、これら2つの行を持っている: :title->#text->Title1
note->#text->Notetest1
私はちょうどのような行のいずれかを使用する場合:私は、コードを実行すると
item.setNote("Notetest1");
item.setTitle("Title1");
私はこの出力を取得
item.setNote("Notetest1");
// item.setTitle("Title1"); /*commented out*/
私はこの出力を得る:
item->note->null
なぜノートは、私はちょうどその値を設定し、setTitle()
を呼び出すと、私はその全体のコード
setNote
とsetTitle?
public class JavaXML {
public static void main(String[] args) throws ParserConfigurationException, JAXBException, FileNotFoundException {
Item item = new Item();
JAXBContext jaxb = JAXBContext.newInstance(item.getClass().getPackage().getName());
Marshaller marshaller = jaxb.createMarshaller();
item.setNote("Notetest1");
item.setTitle("Title1");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
marshaller.marshal(item, doc);
NodeList nodeList = doc.getChildNodes();
recursiveNodeList(nodeList);
}
public static void recursiveNodeList(NodeList nodeList) {
for(int i = 0; i< nodeList.getLength(); i++) {
Node fstNode = nodeList.item(i);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
if(fstElmnt.getChildNodes().getLength() > 1) {
NodeList fstNmElmntLst = fstElmnt.getChildNodes();
recursiveNodeList(fstNmElmntLst);
} else {
NodeList fstNmElmntLst = fstElmnt.getChildNodes();
if(((Node)fstNmElmntLst.item(0)) != null)
System.out.println(fstNode.getNodeName()+"->"+((Node)fstNmElmntLst.item(0)).getNodeName() + "->"+((Node)fstNmElmntLst.item(0)).getNodeValue());
}
}
}
}
}
を編集
別の質問: タイトルとメモを設定する代わりに、次のようなカテゴリを設定してください:
Category category = new Category();
category.setStringOne("string1");
category.setStringTwo("string2");
item.setCategory(category);
その後、出力は次のようになります。
item->category->string1string2
は、文字列操作技術を使用せずに別の変数に「文字列1」と「文字列2」の値を取得する方法はありますか?
はどうもありがとうございました!以前はXMLで作業していませんでしたが、ノードはいつTextノードになるのですか? – Rox
また、私の他の質問を見てください。上記の私の投稿で、私の編集を見てください(太字で表示)。 – Rox
@Rox - 更新した内容に基づいて自分の回答を更新しました。また使いやすいと思われる方法を提供しました。 –