Java调用Document.getElementById方法返回null的解决办法

  Java中操作xml的函数Document.getElementById(String id),是通过指定的id来获取对应的element。但是仅仅定义了正确的schema和对应的xml文件是不够的,返回值仍然是null。因为我们不仅要告诉xml文件我们所用的schema是哪个,还需要告诉Java的parser使用哪个schema来验证,否则parser就没法通过schema来验证xml文件内容,导致Document.getElementById(String id)方法返回null。

  为了告诉Java的parser使用哪个schema,需要在调用DocumentBuilderFactory.newDocumentBuilder()之前给DocumentBuilderFactory设置对应的属性。

  主要代码如下:

 

getTextById(String id)
1 public String getTextById(String id) {
2
3 String text = null;
4
5 // xml and schema file path
6   File xmlFile = new File(this.xml_path);
7 File schemaFile = new File(this.schema_path);
8
9 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
10 // important
11   factory.setNamespaceAware(true);
12 // you should add this to tell Java to validate the schema
13   factory.setValidating(true);
14
15 DocumentBuilder parser = null;
16 Document doc = null;
17
18 try {
19 // important
20   factory.setAttribute(SCHEMA_LANG,XML_SCHEMA);
21 factory.setAttribute(SCHEMA_SOURCE, schemaFile);
22
23 parser = factory.newDocumentBuilder();
24 doc = parser.parse(xmlFile);
25 text = doc.getElementById(id).getTextContent();
26 }
27 catch(Exception e) {
28 System.out.println(e.getMessage());
29 }
30
31 return text;
32 }

 

  现在你就可以根据id获取到xml中的内容了。

  参考:http://crumpling-rumblings.blogspot.com/2008/05/java-how-to-make-getelementbyid-work.html

 

  源代码下载:xmlParser

posted @ 2010-02-06 17:13  轩辕枯藤  阅读(7435)  评论(0编辑  收藏  举报