2010-08-06 68 views
1

爪哇的Xerces 2.9.1插入XML:空間= '保留' 在DOM

insertHere.setAttributeNS(XMLConstants.XML_NS_URI, "xml:space", "preserve"); 

insertHere.setAttributeNS(XMLConstants.XML_NS_URI, "space", "preserve") 

都結束了的只是space='preserve',沒有XML前綴的屬性。

insertHere.setAttribute("xml:space", "preserve") 

的作品,但它似乎有點不對。我錯過了什麼?

編輯

我檢查。

我在setNamespaceAware打開的情況下閱讀了一個模板文檔。

然後,我使用以下來製作它的副本,然後我開始插入新的元素。

public static Document copyDocument(Document input) { 
     DocumentType oldDocType = input.getDoctype(); 
     DocumentType newDocType = null; 
     Document newDoc; 
     String oldNamespaceUri = input.getDocumentElement().getNamespaceURI(); 
     if (oldDocType != null) { 
      // cloning doctypes is 'implementation dependent' 
      String oldDocTypeName = oldDocType.getName(); 
      newDocType = input.getImplementation().createDocumentType(oldDocTypeName, 
                     oldDocType.getPublicId(), 
                     oldDocType.getSystemId()); 
      newDoc = input.getImplementation().createDocument(oldNamespaceUri, oldDocTypeName, 
                   newDocType); 
     } else { 
      newDoc = input.getImplementation().createDocument(oldNamespaceUri, 
                   input.getDocumentElement().getNodeName(), 
                   null); 
     } 
     Element newDocElement = (Element)newDoc.importNode(input.getDocumentElement(), true); 
     newDoc.replaceChild(newDocElement, newDoc.getDocumentElement()); 
     return newDoc; 
    } 

回答

1

當我運行下面的代碼:

import javax.xml.XMLConstants; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import javax.xml.transform.Transformer; 
import javax.xml.transform.TransformerFactory; 
import javax.xml.transform.dom.DOMSource; 
import javax.xml.transform.stream.StreamResult; 

import org.w3c.dom.Document; 
import org.w3c.dom.Element; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     dbf.setNamespaceAware(true); 
     DocumentBuilder db = dbf.newDocumentBuilder(); 
     Document document = db.newDocument(); 

     Element rootElement = document.createElement("root"); 
     document.appendChild(rootElement); 
     rootElement.setAttributeNS(XMLConstants.XML_NS_URI, "space", "preserve"); 

     TransformerFactory tf = TransformerFactory.newInstance(); 
     Transformer t = tf.newTransformer(); 
     t.transform(new DOMSource(document), new StreamResult(System.out)); 
    } 

} 

我得到以下輸出:

<root xml:space="preserve"/> 

你如何建立你的文件嗎?

+0

不知何故,我懷疑我忘了'setNamespaceAware'。 – bmargulies 2010-08-12 17:43:34