-1
我已經看到了一些舊的答案左右,但我不覺得對於這種特殊情況下的解決方案。編寫XML命名空間在Java中
我正在尋找下一個輸出:
<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">
<manifest:file-entry manifest:full-path="/" manifest:version="1.2" manifest:media-type="application/vnd.oasis.opendocument.spreadsheet"/>
</manifest:manifest>
所以,我試了下代碼:
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test {
public static void main(String args[]){
final String MIMETYPE = "application/vnd.oasis.opendocument.spreadsheet";
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.newDocument();
Element e = null;
Element rootEle = dom.createElementNS("manifest","manifest");
rootEle.setAttributeNS("manifest","version","1.2");
rootEle.setAttributeNS("xmlns","manifest","urn:oasis:names:tc:opendocument:xmlns:manifest:1.0");
e = dom.createElementNS("manifest","file-entry");
e.setAttributeNS("manifest","full-path","/");
e.setAttributeNS("manifest","version","1.2");
e.setAttributeNS("manifest","media-type",MIMETYPE);
rootEle.appendChild(e);
dom.appendChild(rootEle);
try {
Transformer tr = TransformerFactory.newInstance().newTransformer();
tr.setOutputProperty(OutputKeys.INDENT, "yes");
tr.setOutputProperty(OutputKeys.METHOD, "xml");
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
FileOutputStream o = new FileOutputStream("Output.xml");
tr.transform(new DOMSource(dom),
new StreamResult(o));
o.close();
} catch (TransformerException te) {
System.err.println(te.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
} catch (ParserConfigurationException pce) {
System.err.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
}
}
}
我得到一個輸出:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<manifest xmlns:ns0="xmlns" ns0:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" xmlns:ns1="manifest" ns1:version="1.2" xmlns="manifest">
<file-entry xmlns:ns0="manifest" ns0:full-path="/" ns1:media-type="application/vnd.oasis.opendocument.spreadsheet" xmlns:ns2="manifest" ns2:version="1.2"/>
</manifest>
它搞亂了命名空間!我怎樣才能得到正確的輸出?
請在您的問題中添加想要生成的所需輸出。 – Progman
@Progman我已經做 – amchacon
需要它,所有的元素和屬性有「明顯的」前綴,即使他們可以(至少在這個例子中)被忽略? – Progman