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设置对应的属性。

  主要代码如下:

 

复制代码
   
   
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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值