1. 程式人生 > >Java呼叫Document.getElementById方法返回null的解決辦法

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 // important11 factory.setNamespaceAware(true);
12 // you should add this to tell Java to validate the schema13 factory.setValidating(true);
14 15 DocumentBuilder parser =null;
16 Document doc =null;
17 18 try {
19 // important20 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中的內容了。