【发布时间】:2015-12-08 13:24:26
【问题描述】:
大家好,我正在编写这个程序:
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class DOMbooks {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
File file = new File("books-fixed.xml");
Document doc = docBuilder.parse(file);
NodeList list = doc.getElementsByTagName("*");
int bookCounter = 1;
for (int i = 1; i < list.getLength(); i++) {
Element element = (Element)list.item(i);
String nodeName = element.getNodeName();
if (nodeName.equals("book")) {
bookCounter++;
System.out.println("BOOK " + bookCounter);
String isbn = element.getAttribute("sequence");
System.out.println("\tsequence:\t" + isbn);
}
else if (nodeName.equals("author")) {
System.out.println("\tAuthor:\t" + element.getChildNodes().item(0).getNodeValue());
}
else if (nodeName.equals("title")) {
System.out.println("\tTitle:\t" + element.getChildNodes().item(0).getNodeValue());
}
else if (nodeName.equals("publishYear")) {
System.out.println("\tpublishYear:\t" + element.getChildNodes().item(0).getNodeValue());
}
else if (nodeName.equals("genre")) {
System.out.println("\tgenre:\t" + element.getChildNodes().item(0).getNodeValue());
}
}
}
}
我想打印有关“科幻小说”书籍的所有数据。我知道我应该使用 Xpath,但它卡住了,错误太多...有什么建议吗? 假设我有这张桌子,我只想选择带有所有信息的科幻书籍
<book sequence="5">
<title>Aftershock</title>
<auther>Robert B. Reich</auther>
<publishYear>2010</publishYear>
<genre>Economics</genre>
</book>
- <book sequence="6">
<title>The Time Machine</title>
<auther>H.G. Wells</auther>
<publishYear>1895</publishYear>
<genre>Science Fiction</genre>
假设我有这张桌子,我只想打印包含所有信息的科幻书籍...
【问题讨论】:
-
为什么 XPath 卡住了太多错误?它作为查询 XML 的事实工具已有超过 15 年的历史,并且一直非常稳定。您使用什么处理器遇到错误(假设您的意思是处理器中的错误)?
-
是的,我删除了我编写 Xpath 块的部分,实际上它是垃圾..我导入了许多不必要的包并编写了许多不必要的代码行,我对它完全陌生..我正在尝试已经 4 小时了,但似乎没有任何效果
-
让我们后退一步。您为什么不向我们展示输入 XML 的一个(小但相关的)部分,对于预期的输出 XML 也是如此。也许 XPath 不好,你需要 XSLT。许多人将 Java 与 XML 技术一起使用没有问题,但使用像您现在这样更难的技术会使情况变得更糟......(imo)
-
我编辑了,你现在可以吃鸡了...