2012-08-07 100 views
1

我有這樣的代碼:Java的XML命名空間的問題

org.w3c.dom.Document doc = docBuilder.parse(representation.getStream()); 
       Element element = doc.getDocumentElement(); 
       NodeList nodeList = element.getElementsByTagName("xnat:MRSession.scan.file"); 
       for (int i = 0; i < nodeList.getLength(); i++) { 
        Node node = nodeList.item(i); 
        if (node.getNodeType() == Node.ELEMENT_NODE) { 
         // do something with the current element 

我的問題是getElementsByTagName("xnat:MRSession.scan.file")

我的XML看起來是這樣的:

<?xml version="1.0" encoding="UTF-8"?><xnat:MRSession "REMOVED DATA IGNORE"> 
<xnat:sharing> 
<xnat:share label="23_MR1" project="BOGUS_GSU"> 
<!--hidden_fields[xnat_experimentData_share_id="1",sharing_share_xnat_experimentDa_id="xnat_E00001"]--> 
</xnat:share> 
</xnat:sharing> 
<xnat:fields> 
<xnat:field name="studyComments"> 
<!--hidden_fields[xnat_experimentData_field_id="1",fields_field_xnat_experimentDat_id="xnat_E00001"]-->S</xnat:field> 
</xnat:fields> 
<xnat:subject_ID>xnat_S00002</xnat:subject_ID> 
<xnat:scanner manufacturer="GE MEDICAL SYSTEMS" model="GENESIS_SIGNA"/> 
<xnat:prearchivePath>/home/ryan/xnat_data/prearchive/BOGUS_OUA/20120717_131900137/23_MR1</xnat:prearchivePath> 
<xnat:scans> 
<xnat:scan ID="1" UID="1.2.840.113654.2.45.2.108830" type="SAG LOCALIZER" xsi:type="xnat:mrScanData"> 
<!--hidden_fields[xnat_imageScanData_id="1"]--> 
<xnat:image_session_ID>xnat_E00001</xnat:image_session_ID> 
<xnat:quality>usable</xnat:quality> 
<xnat:series_description>SAG LOCALIZER</xnat:series_description> 
<xnat:scanner manufacturer="GE MEDICAL SYSTEMS" model="GENESIS_SIGNA"/> 
<xnat:frames>29</xnat:frames> 
<xnat:file URI="/home/ryan/xnat_data/archive/BOGUS_OUA/arc001/23_MR1/SCANS/1/DICOM/scan_1_catalog.xml" content="RAW" file_count="29" file_size="3968052" format="DICOM" label="DICOM" xsi:type="xnat:resourceCatalog"> 

所以基本上我需要能夠在所有的xnat迭代:MRSession/xnat:掃描/ xnat:文件 元素和做出一些改變。問題是

getElementsByTagName("xnat:MRSession.scan.file") 

始終爲空。請幫忙。由於

+2

什麼文檔中讓你覺得它應該工作你使用它的方式嗎? – parsifal 2012-08-07 19:18:36

+0

我的文檔還不清楚。我只需要知道特定xnat:file元素的正確語法。任何你可以照耀的光線都會很有幫助。顯然我錯過了一些東西。 – rpfujiw 2012-08-07 19:22:15

+1

在我看來,你需要的是xPath,而不是'getElementsByTagName'。 – 2012-08-07 19:33:59

回答

1

你可以嘗試以下方法使用XPath:

Document document = // the parsed document 
XPathFactory xPathFactory = XPathFactory.newInstance(); 
NodeList allFileNodes = xPathFactory.newXPath().evaluate("\\XNAT_NAMESPACE:file", document.getDocumentElement(), XPathConstants.NODESET); 

相反XNAT_NAMESPACE你需要指定是指具有在你的榜樣前綴「xnat」確切的命名空間。