Java DOM XML正在跳过xmlns属性

时间:2009-08-18 16:24:38

标签: java xml dom xml-namespaces

我需要用Java生成一个xml文件,所以我选择使用DOM(直到一切正常),这里是我需要创建的根标记

<?xml version="1.0" encoding="utf-8"?>
<KeyContainer Version="1.0" xmlns="urn:ietf:params:xml:ns:keyprov:pskc:1.0" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xml="http://www.w3.org/XML/1998/namespace">

这是我的源代码

PrintWriter out = new PrintWriter(path);
Document xmldoc = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        DOMImplementation impl = builder.getDOMImplementation();
        Element e = null;
        Node n = null;
        xmldoc = impl.createDocument(null, "KeyContainer", null);
        /* Noeuds non bouclés */
        Element keycontainer = xmldoc.getDocumentElement();
            keycontainer.setAttributeNS(null, "Version", "1.0");
            keycontainer.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:ds","http://www.w3.org/2000/09/xmldsig#");
            keycontainer.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#");
            keycontainer.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xml", "http://www.w3.org/XML/1998/namespace");
            keycontainer.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:ietf:params:xml:ns:keyprov:pskc:1.0");
/* Non relevant Info*/
DOMSource domSource = new DOMSource(xmldoc);
        StreamResult streamResult = new StreamResult(out);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer serializer = tf.newTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING,"utf-8");
        serializer.setOutputProperty(OutputKeys.VERSION,"1.0");
        serializer.setOutputProperty(OutputKeys.INDENT,"yes");
        serializer.setOutputProperty(OutputKeys.STANDALONE,"yes");
        serializer.transform(domSource, streamResult); 

这就是我得到的

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<KeyContainer xmlns="" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Version="1.0">

问题是xmlns属性为空,缺少xmlns:xml,我该怎么做才能获取所有信息?

非常感谢stackoverflow

(PS:在NamespaceURI字段中除了“http://www.w3.org/2000/xmlns/”之外还有NAMESPACE_ERR)

2 个答案:

答案 0 :(得分:4)

要摆脱xmlns=""

,需要做两件事

使用所需的名称空间URI创建Document

xmldoc = impl.createDocument("urn:ietf:params:xml:ns:keyprov:pskc:1.0", "KeyContainer", null);

删除以下行,因为现在不需要:

keycontainer.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:ietf:params:xml:ns:keyprov:pskc:1.0");

关于xmlns:xml属性,API正在默默地删除它。见NamespaceMappings第173行。一些研究表明,声明特定命名空间的行为是未定义的,不推荐使用。

答案 1 :(得分:4)

要使DOM名称空间可识别,请不要忘记使用setNamespaceAware方法在documentbuilderfactory中启用它。