Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating namespace prefixed XML nodes in Java DOM

I am creating several XML files via Java and up to this point everything worked fine, but now I've run into a problem when trying to create a file with namespace prefixed nodes, i.e, stuff like <tns:node> ... </tns:node> using a refactored version of my code that's already working for normal xml files without namespaces.

The error getting thrown is:

org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: Ungültiges XML-Zeichen angegeben. 

Sorry for the German in there, it says "invalid XML-sign specified".

The codeline where the error occurs:

Element mainRootElement = doc.createElement("tns:cmds xmlns:tns=\"http://abc.de/x/y/z\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://abc.de/x/y/z xyzschema.xsd\"");

To eliminate the possibility of the error resulting in escaping that rather long string or something among those lines I also tried just using Element mainRootElement = doc.createElement("tns:cmds");, however, this results in the same error.

That's why I figure it has something to do with the namespace declaration, i.e., the : used to do it, as that's the only "invalid" character I could think of in that string.

Can anyone confirm this is the source of the problem? If so, is there an easy solution to it? Can Java DOM use namespaced tags at all?

Edit: Whole method for reference

private void generateScriptXML()
    {
        DocumentBuilderFactory icFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder icBuilder;
        try
        {
            icBuilder = icFactory.newDocumentBuilder();
            Document doc = icBuilder.newDocument();

            Element mainRootElement = doc.createElement("tns:cmds xmlns:tns=\"http://abc.de/x/y/z\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://abc.de/x/y/z xyzschema.xsd\"");

            doc.appendChild(mainRootElement);
            mainRootElement.appendChild(getAttributes(doc,"xxx", "yyy", "zzz"));
            mainRootElement.appendChild(getAttributes(doc,"aaa", "bbb", "ccc"));
            mainRootElement.appendChild(getAttributes(doc,"ddd", "eee", "fff"));
            ...
            ...

            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(doc);
            StreamResult streamResult = new StreamResult(new File(vfsPath));
            transformer.transform(source, streamResult);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
like image 326
daZza Avatar asked Feb 13 '15 09:02

daZza


People also ask

How do you create a namespace prefix in XML?

When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".

What is namespace in Dom?

The XML Document Object Model (DOM) is completely namespace-aware. Only namespace-aware XML documents are supported. The World Wide Web Consortium (W3C) specifies that DOM applications that implement Level 1 can be non-namespace-aware, and DOM Level 2 features are namespace-aware.

What is an XML namespace prefix used for?

An XML namespace is a collection of names that can be used as element or attribute names in an XML document. The namespace qualifies element names uniquely on the Web in order to avoid conflicts between elements with the same name.


1 Answers

Wrong method, try the *NS variants:

Element mainRootElement = doc.createElementNS(
   "http://abc.de/x/y/z", // namespace
   "tns:cmds" // node name including prefix
);

First argument is the namespace, second the node name including the prefix/alias. Namespace definitions will be added automatically for the namespace if needed. It works to set them as attributes, too.

The namespace in your original source is http://abc.de/x/y/z. With the attribute xmlns:tns="http://abc.de/x/y/z" the alias/prefix tns is defined for the namespace. The DOM api will implicitly add namespaces for nodes created with the *NS methods.

xmlns and xml are reserved/default namespace prefixes for specific namespaces. The namespace for xmlns (namespace definitions) is http://www.w3.org/2000/xmlns/.

To add an xmlns:* attribute with setAttributeNS() use the xmlns namespace:

mainRootElement.setAttributeNS(
  "http://www.w3.org/2000/xmlns/", // namespace
  "xmlns:xsi", // node name including prefix
  "http://www.w3.org/2001/XMLSchema-instance" // value
);

But even that is not needed. Just like for elements, the namespace definition will be added implicitly if you add an attribute node using it.

mainRootElement.setAttributeNS(
  "http://www.w3.org/2001/XMLSchema-instance", // namespace
  "xsi:schemaLocation", // node name including prefix
  "http://abc.de/x/y/z xyzschema.xsd" // value
);

Namespaces Prefixes

If you see a nodename like xsi:schemaLocation you can resolve by looking for the xmlns:xsi attribute. This attribute is the namepace definition. The value is the actual namespace. So if you have an attribute xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" the node name can be resolved to {http://www.w3.org/2001/XMLSchema-instance}schemaLocation (Clark notation).

If you want to create the node you need 3 values:

  1. the namespace: http://www.w3.org/2001/XMLSchema-instance
  2. the local node name: schemaLocation
  3. the prefix: xsi

The prefix is optional for element nodes, but mandatory for attribute nodes. The following three XMLs resolve all to the element node name {http://abc.de/x/y/z}cmds:

  • <tns:cmds xmlns:tns="http://abc.de/x/y/z"/>
  • <cmds xmlns="http://abc.de/x/y/z"/>
  • <other:cmds xmlns:other="http://abc.de/x/y/z"/>
like image 193
ThW Avatar answered Oct 07 '22 01:10

ThW