【问题标题】:Java DOM: How to add a namespace with a specific prefix?Java DOM:如何添加具有特定前缀的命名空间?
【发布时间】:2014-05-24 10:14:29
【问题描述】:

我正在尝试用 Java 为 Android 构建一个简单的 XML DOM。这工作正常,但 Android 命名空间前缀始终设置为“ns0”,但它应该是“android”

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);

doc = factory.newDocumentBuilder().newDocument();
doc.setXmlStandalone(true);

Element manifest = doc.createElement("manifest");
manifest.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:android",NS_ANDROID);
manifest.setAttributeNS(NS_ANDROID, "versionName", "bla");
doc.appendChild(manifest);

我得到的输出如下:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:ns0="http://schemas.android.com/apk/res/android" ns0:versionName="bla"/>

我需要改变什么才能得到以下结果:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
android:versionName="bla"/>

【问题讨论】:

    标签: java xml xml-namespaces


    【解决方案1】:

    setAttributeNS() 方法需要 QName。在您的第二次调用中,您传递了一个不合格的属性名称,因此添加了一个默认前缀 (ns0)。由于您调用了两次,因此您有两个属性。

    要获得您期望的结果,您只需使用 qualified 属性名称调用一次setAttributeNS()

    Element manifest = doc.createElement("manifest");
    manifest.setAttributeNS(NS_ANDROID, "android:versionName", "bla");
    doc.appendChild(manifest);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多