2015-04-08 13 views
0

我正在嘗試向xml文檔添加元素。元素可以成功添加,但問題是,解析器會在其他位置修改原始xml文件,例如,它會交換名稱空間和id屬性或刪除重複的名稱空間定義。我只需要添加特定的元素就可以得到完全相同的文檔(相同的語法,保留空格)。我將不勝感激任何建議。這裏是我的代碼:在沒有文檔修改的情況下使用javax分析器向XML添加元素

public void appendTimestamp(String timestamp, String signedXMLFile, String timestampedXMLFile){ 
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 

    try{ 
     DocumentBuilder builder = factory.newDocumentBuilder(); 
     Document doc = builder.parse(new File(signedXMLFile)); 

     XPath xPath = XPathFactory.newInstance().newXPath(); 
     NodeList list = (NodeList)xPath.evaluate("//*[local-name()='Signature']/*[local-name()='Object']/*[local-name()='QualifyingProperties']", doc, XPathConstants.NODESET); 

     if(list.getLength() != 1){ 
      throw new Exception(); 
     } 

     Node node = list.item(0); 
     Node unsignedProps = doc.createElement("xades:UnsignedProperties"); 
     Node unsignedSignatureProps = doc.createElement("xzep:UnsignedSignatureProperties"); 
     Node timestampNode = doc.createElement("xzep:SignatureTimeStamp"); 
     timestampNode.appendChild(doc.createTextNode(timestamp)); 

     unsignedSignatureProps.appendChild(timestampNode); 
     unsignedProps.appendChild(unsignedSignatureProps); 
     node.appendChild(unsignedProps); 

     Transformer transformer = TransformerFactory.newInstance().newTransformer(); 
     transformer.setOutputProperty(OutputKeys.INDENT, "no"); 
     transformer.setOutputProperty(OutputKeys.METHOD, "xml"); 
     transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 

     DOMSource source = new DOMSource(doc); 

     StringWriter writer = new StringWriter(); 
     StreamResult stringWriter = new StreamResult(writer); 
     transformer.transform(source, stringWriter); 

     writer.flush(); 
     System.out.println(writer.toString()); 

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

原始XML文件:

...  
<ds:Object Id="objectIdVerificationObject" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> 
... 

修改的XML文件:

... 
<ds:Object xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="objectIdVerificationObject"> 
... 
+0

作爲一個快速和髒的修復(如果這是緊急),請考慮修改您的代碼在字符串級別的最終輸出以交換這些屬性? – Kris

回答

0

如果使用DOM模型,那麼整個XML文件讀取,然後在存儲器中表示爲節點樹,然後以由作者確定的方式保存到xml中。所以幾乎不可能保留原始的xml格式,因爲您無法控制它,例如節點樹中根本沒有表示空格。

您需要部分讀取原始xml並將其內容輸出到新文件中,以保留讀取的內容,然後在「正確」的位置添加新內容並繼續簡單合併原始內容。

例如,您可以使用XMLStreamWriterXMLStreamReader來實現,因爲它們提供「低」級別的操作。

但是,將xml作爲文本行復制一次,直到您識別插入點,然後創建新的xml部分並將其附加爲文本並繼續進行復制,可能會更容易。

+0

感謝您的回覆。我想利用xpath和方便的節點操作,因此將xml作爲文本處理是我最後的選擇。到目前爲止,我沒有遇到解決方案如何解析xml而無需解析器修改元素。最後,我按照你的建議做了,並將xml加載到字符串中,然後在所需的位置插入xml部分。 – EddGarcia

相關問題