2011-07-24 40 views
1

我試圖解析下列字符串以形成一個xml文檔,然後嘗試提取所有子節點並添加到已經提供給我的不同文檔對象。混合文本和元素節點時,XML子節點迭代的問題

<dhruba><test>this</test>that<test2>wang chu</test2> something.... </dhruba> 

<dhruba>this is text node <test>this</test>that<test2>wang chu</test2> anything..</dhruba> 

,而我想讀的子節點,則返回null孩子TEXT_NODE爲1弦和空值ELEMENT_NODE的第二根弦,這是錯誤的,是API的問題?

我使用下面的代碼...它編譯,我用java 6

 Node n = null; 
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
       try { 
        db = dbf.newDocumentBuilder(); 
       } catch (ParserConfigurationException e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } 
       dom = db.newDocument(); 
       Element rootEle = dom.createElement("resources"); 
     // adding the root element to the document 
     dom.appendChild(rootEle); 

     Element element = dom.createElement("string"); 

     element.setAttribute("name", "some_name"); 
     try { 

      n = db.parse(new InputSource(new StringReader("<dhruba><test>this</test>that<test2>node value</test2> some text</dhruba>"))).getDocumentElement(); 
      n = dom.importNode(n, true); 


      NodeList nodeList = n.getChildNodes(); 
      int length = nodeList.getLength(); 
      System.out.println("Total no of childs : "+length); 
      for(int count = 0 ; count < length ; count++){ 
       Node node = nodeList.item(count); 
       if(node != null){ 
        element.appendChild(node); 
       } 
      } 
     } catch (SAXException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     rootEle.appendChild(element); 

INPUT ::作爲字符串

   <dhruba><string name="some_name"> 
         that 
         <test>this</test>        
         <test2>node value</test2> 
         some text 
        </string> 
       </dhruba> 

預期產出::作爲文檔

   <string> 
       <string name="some_name"> 
          <test>this</test> 
          <test2>node value</test2> 
       </string> 
       </string> 

如果我試圖解析

  <test>this</test>that<test2>wang chu</test2> something.... 

然後輸出當屬 「thiswang楚」

Why is this happening? what needs to be done if I want to add following node under another document element, i.e. <string>. 
    <test>this</test> 
         that        
         <test2>node value</test2> 
         some text 
[notice that it does not have <dhruba>] inside parent node of another 
document. 

希望我是清楚的。以上代碼在Java編譯6

回答

0

也許你想Node.cloneNode()方法:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder(); 

Document dom = db.newDocument(); 

Element element = dom.createElement("string"); 
element.setAttribute("name", "some_name"); 

String inputXMLString = 
    "<dhruba><test>this</test>that<test2>node value</test2> some text</dhruba>"; 
Node n = db.parse(new InputSource(new StringReader(inputXMLString))).getDocumentElement(); 
n = dom.importNode(n, true); 

NodeList nodeList = n.getChildNodes(); 
for (int i = 0; i < nodeList.getLength(); ++i) 
{ 
    Node node = nodeList.item(i); 
    element.appendChild(node.cloneNode(true)); 
} 
dom.appendChild(element); 

要獲得dom到標準輸出或文件,你可以寫:

TransformerFactory tFactory = TransformerFactory.newInstance(); 
Transformer transformer = tFactory.newTransformer(); 
transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 
DOMSource source = new DOMSource(dom); 
StreamResult result = new StreamResult(System.out); 
transformer.transform(source, result); 

結果:

<string name="some_name"> 
<test>this</test>that<test2>node value</test2> some text</string> 
+0

非常感謝Grzegorz,cloneNode(true)工作正常。你爲我節省了更多的時間。 – Dhrubo

+0

@Dhrubo:不客氣:)您可能會將我的答案標記爲已接受(http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) –

+0

如何接受?我在這個網站是新的..請指導。我已經使用上面的鏈接,但它是一個meta.stackoverflow網站,我很困惑點擊什麼.. :( – Dhrubo

1

我會假設這是Java。

首先,我很驚訝你不會因爲你的importNode()調用而遇到異常,因爲你正在導入Document,這不應該被允許(根據JavaDoc)。

現在您所問的問題是:如果您只想附加特定的節點類型,則需要使用該節點的類型進行測試。一個switch語句是最簡單的(注意:這還沒有被編譯,可能含有語法錯誤):

switch (n.getNodeType()) 
{ 
    case ELEMENT_NODE : 
     // append the node to the other tree 
     break; 
    default : 
     // do nothing 
} 
+1

不,importNode正在返回節點,如果我添加父節點,即而不是試圖添加它的子節點,它會添加罰款並生成良好的輸出,但與父元素,我不想要。另外,我需要所有類型的節點,TEXT_NODE或ELEMENT_NODE,所以我沒有使用檢查,並且令人驚訝的是,根據給定的輸入,它對任何一個節點類型都返回null。 – Dhrubo

+0

@dhrubo:好的,在那種情況下,我不知道你在做什麼。我建議你編輯你的文章以包含*完整的*,*可編輯的*例子。然後顯示輸入,實際輸出和預期輸出。但是,我可以向你保證的一件事是:*它不是** API的問題。 – parsifal

+0

已修改,請讓我知道是否需要進一步說明,並注意上面的代碼編譯。我目前正在使用這個代碼,我剛剛改變了我的變量。 – Dhrubo