代码之家  ›  专栏  ›  技术社区  ›  user205512

XMLOutputStream,修复名称空间和没有名称空间的属性

  •  1
  • user205512  · 技术社区  · 16 年前

    一个简单的任务:为元素编写两个属性:

    String nsURI = "http://example.com/";
    XMLOutputFactory outF = XMLOutputFactory.newFactory();
    outF.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
    XMLStreamWriter out = outF.createXMLStreamWriter(System.out);
    out.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "element", nsURI);
    out.writeAttribute("attribute", "value");
    out.writeAttribute("attribute2", "value");
    out.writeEndElement();
    out.close();
    

    <element xmlns="http://example.com/" attribute="value" attribute2="value"></element>
    

    <zdef-1905523464:element xmlns="" xmlns:zdef-1905523464="http://example.com/" attribute="value" attribute2="value"></zdef-1905523464:element>
    

    此外,如果我们为元素添加前缀:

    out.writeStartElement("ns", "element", nsURI);
    

    JDK 6不再尝试发出xmlns=“”:

    <ns:element xmlns:ns="http://example.com/" attribute="value" attribute2="value"></ns:element>
    

    如果我们删除了一个属性(即只有一个属性),就可以了。

    我很确定这是JDK6中的一个bug,对吗?有谁能提出一个能让两个图书馆(以及其他图书馆)都满意的解决方案吗?如果我能帮忙的话,我不想要求伍德斯托克斯。

    2 回复  |  直到 16 年前
        1
  •  2
  •   MarcoS    16 年前

    我想你必须告诉警察 XMLStreamWriter 默认命名空间是什么,然后在添加元素时使用它:

    String nsURI = "http://example.com/";
    XMLOutputFactory outF = XMLOutputFactory.newFactory();
    outF.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
    XMLStreamWriter out = outF.createXMLStreamWriter(System.out);
    out.setDefaultNamespace(nsURI);
    out.writeStartElement(nsURI, "element");
    out.writeAttribute("attribute", "value");
    out.writeAttribute("attribute2", "value");
    out.writeEndElement();
    out.close();
    

    上面的代码提供了以下输出:

    <element xmlns="http://example.com/" 
        attribute="value" attribute2="value"></element>
    

    使用java版本“1.6.0\U 20”

        2
  •  1
  •   StaxMan    15 年前

    我的建议是永远不要依赖writeAttribute()的2参数版本,因为它到底应该输出什么的定义并不清楚:它应该使用namespace“”(也称为“no namespace”)还是当前默认的名称空间?这尤其令人困惑,因为根据XML规范,属性从不使用默认名称空间(仅显式名称空间)。因此,可以说,所有表达的行为都可能被视为是正确的;但显然他们不可能都是。只是staxapi没有正确定义(AFAIK)真正的答案应该是什么(这很糟糕)。

    所以:只需指定属性应该使用的名称空间(“no namespace”可以使用“null”或“no namespace”),事情应该会更好。

    据我所知,JDK版本的问题是,有些版本假设属性实际上使用了默认名称空间;这就是为什么添加了假“xmlns=”“”。这是不必要的。

    推荐文章