1

I am trying to build a simple XML DOM in Java for Android. This works fine but the Android namespace prefix is always set to "ns0" but it should be "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);

The output I get is the following:

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

What do I need to change to get the following result:

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

1 Answer 1

1

The setAttributeNS() method requires a QName. In your second call you passed an unqualified attribute name, so a default prefix (ns0) was added to it. Since you called it twice, you got two attributes.

To obtain the result you expect, you just have to call setAttributeNS() once with a qualified attribute name:

Element manifest = doc.createElement("manifest");
manifest.setAttributeNS(NS_ANDROID, "android:versionName", "bla");
doc.appendChild(manifest);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.