2017-05-26 43 views
1

我試圖創建一個結構,一個新的XML,並在同一時間通過這個如何創建一個新的XML文件Joox

String styleName = "myStyle"; 
String styleKey = "styleKeyValue"; 

File file = new File("test.xml");   

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder builder = dbf.newDocumentBuilder(); 
Document document = builder.newDocument(); 

Match x = $(document) 
       .namespace("s", "http://www.mycompany.com/data") 
       .append(
        $("Data", 
         $("Styles", 
          $("Style", 
           $("Attributes", "") 
          ).attr("name", styleName) 
         ) 
        ) 
       ); 

Match xpath = x.xpath("//s:Attributes"); 

xpath = xpath.append($("Attribute", "").attr("key", styleKey)); 

x.write(file); 

添加元素然而.append似乎不添加任何東西最後我得到一個空文件。
此方法基於this SO answer,但「Document document = $(file).document();」行給我一個例外,因爲該文件不存在 - 因此使用DocumentBuilder。

當然,我意識到我可以通過其他方法創建新的xml文件,我現在試圖堅持使用基於Joox的方法。

回答

2

盧卡斯埃德爾工作反饋後的版本(Joox「一路」選項)

// Initial block to create xml structure 
Match x = $("Data", 
      $("Styles", 
       $("Style", 
        $("Attributes", "")            
       ).attr("name", styleName) 
      ) 
      ).attr("xmlns", "http://www.mycompany.com/data"); 

// example xpath into structure to add element attribues 
// as required 
Match xpath = x.xpath("//Attributes"); 

xpath = xpath.append($("Attribute", "").attr("key", styleKey)); 

x.write(file); 

產生如下:

<Data xmlns="http://www.mycompany.com/data"> 
    <Styles> 
     <Style name="myStyle"> 
      <Attributes> 
       <Attribute key="styleKeyValue"/> 
      </Attributes> 
     </Style> 
    </Styles> 
</Data> 
1

這裏的問題是對Match.append()做什麼的誤解。讓我們來看看它這樣

Javadoc寫着:

追加內容到匹配的元素集合中每個元素的內容結束。現在

,如果你這樣做:

Match x = $(document); 

這只是包裝在jOOX Match包裝進行進一步處理現有的文檔。這個Match包裝根本沒有匹配任何元素,因爲包裝的document中沒有元素,甚至沒有根元素(您創建了一個新元素)。所以,實際上爲了創建內容的文件,你必須:

  • 無論是使用DOM API
  • 創建的根元素或者使用jOOX一路,因爲可以看到下面:

    Match x = $("Data", 
          $("Styles", 
           $("Style", 
           $("Attributes", "") 
           ).attr("name", styleName) 
          ) 
          ); 
    

請注意,您的通話Match.namespace()沒有你想它有效果。目前沒有辦法設置 jOOX生成的元素上的命名空間。這是此功能的待處理功能請求:https://github.com/jOOQ/jOOX/issues/133

Match.namespace()方法只是將一個名稱空間綁定到匹配上下文中的前綴,用於後續的xpath()調用。下面是該方法的Javadoc中提取:

獲取以供後續的XPath添加命名空間配置一個新的匹配要求

+0

好,謝謝 - 我understan d。我想我期待一場失敗的比賽來拋出一個異常。我意識到我可以使用「if(x.isEmpty())」,但這會阻礙方法鏈式風格。我已經修改了我的代碼沿線(joox一路選項),你建議並得到它的工作 - 將作爲編輯添加到問題.. – Dazed

+0

@Dazed:好主意,順便說一句,你可以提供你自己的答案在這裏堆棧溢出。這是建議您最終解決方案的推薦方式,而不是編輯問題的...... –