2013-12-17 34 views
0

我需要以下概念的幫助。文檔解析顯示爲null

我想在代碼中獲取外部參照節點的屬性。即id及其價值,位置及其價值,類型及其價值。 我傳遞xml作爲字符串。但文檔在解析時顯示爲空。

請幫助我。

import java.io.StringReader; 

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; 
import org.xml.sax.InputSource; 



public class GetAtrribute { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     String xml = "<xref id=\"19703675\" location=\"abstract\" type=\"external\">PubMed Abstract: http://www.abcd.nlm.nih.gov/...</xref>"; //Populated XML String.... 
     GetAtrribute ga = new GetAtrribute(); 
     try { 
      ga.getValues(xml); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 


    } 

    public String getValues(String xmlStr) throws Exception { 
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder builder; 
     xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + xmlStr; 
     try { 
      builder = factory.newDocumentBuilder(); 
      Document document = builder.parse(new InputSource(new StringReader(
        xmlStr))); 
      Element element = document.getDocumentElement(); 

      NodeList list = element.getElementsByTagName("xref"); 
      if (list != null && list.getLength() > 0) { 
       NodeList subList = list.item(0).getChildNodes(); 

       if (subList != null && subList.getLength() > 0) { 
        return subList.item(0).getNodeValue(); 
       } 
       for (int count = 0; count < subList.getLength(); count++) { 
        System.out.println(subList.item(count).getNodeValue()); 
       } 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return xmlStr; 

    } 

} 

回答

0

你的問題是,當你運行該行:

Element element = document.getDocumentElement(); 

你其實選擇外部參照已,因爲它的唯一的XML元素。你可以用xref包裝另一個對象,或者使用變量'element'來獲取細節。

p.s.你的類名拼寫錯誤:GetAtrribute - >的getAttribute

0

我建議你使用XPath找到你的XML數據:

XPath xPath = XPathFactory.newInstance().newXPath(); 
Document baseDoc; 
try (InputStream pStm = new ByteArrayInputStream(baseXmlString.getBytes("utf-8"))) { 
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = factory.newDocumentBuilder(); 
    baseDoc = builder.parse(pStm); 
} catch (SAXException | IOException | ParserConfigurationException ex) { 
    getLogger().error(null, ex); 
    return null; 
} 
try { 
    XPathExpression expression = xPath.compile(xPathExpression); 
    return (T) expression.evaluate(baseDoc, pathType); 
} catch (XPathExpressionException ex) { 
    getLogger().error(null, ex); 
} 
return null; 

例如看看here