gpt4 book ai didi

java - 解析此 XML 时我做错了什么

转载 作者:行者123 更新时间:2023-12-01 14:07:56 24 4
gpt4 key购买 nike

我正在尝试解析具有以下结构的 xml Structure

这是我编写的用于解析它的代码片段

  doc.getDocumentElement().normalize();
System.out.println ("Root element: " +
doc.getDocumentElement().getNodeName());//prints GoodReadsResponse correctly
NodeList bk = doc.getElementsByTagName("book");// single all encompassing element in response

Node n= bk.item(1);// since the 0th node is id the 1st must be the title
System.out.println("Node value"+n.getLocalName());
Element e=(Element)n;
NodeList titleList= e.getElementsByTagName("title");//get the title
Element titleElem = (Element) titleList.item(1);
Node titleNode = titleElem.getChildNodes().item(0);// get the node value
book.setTitle(titleNode.getLocalName());// this prints null instead of printing Hamlet--why??
System.out.println("Title in parser"+titleNode.getLocalName());//null again

编辑:代码中指出的问题是 titleNode.getLocalName() 始终为 null,我无法弄清楚为什么。我已经将我的思想结构作为注释放在代码中。知道为什么会发生这种情况吗?指点将不胜感激!

最佳答案

以下代码

NodeList bk = doc.getElementsByTagName("book"); //This get All BOOKS

返回所有书籍项目的 NodeList,因为您的 xml 中只有一本书,因此您应该遵循此内容

Node n= bk.item(0);

在本例中,n = 书籍节点此外,您还必须对标题执行相同的操作,使其像这样

NodeList titleList= e.getElementsByTagName("title");//get All titles
Element titleElem = (Element) titleList.item(0);

然后你的其余代码应该可以正常工作!

关于java - 解析此 XML 时我做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18753717/

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