'Java Alternative to C#'s WriteAttributeString()
In C#, there's a method to write attributes to an XML element:
public void WriteAttributeString(string? prefix, string localName, string? ns, string? value);
What I have found in Java is:
Attr createAttributeNS(String namespaceURI, String qualifiedName)
But it seems lacking two parameters. As far as I understand, ns == namespaceURI, and localName == qualifiedName.
Is there a similar method to achieve the same thing in Java? Or do I have to implement my own version (consequently, extending Document)?
Solution 1:[1]
You could call setAttributeNS on org.w3c.dom.Element.
Suppose you want to generate an output like the following:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<child xmlns:pfx="http://www.example.com" answer="42"/>
</root>
You could use something similar to the following code:
childElement.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:pfx","http://www.example.com");
childElement.setAttribute("answer", "42");
A complete, self-contained example might look like this:
package com.software7.test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
public class Main {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document document = docBuilder.newDocument();
Element rootElement = document.createElement("root");
document.appendChild(rootElement);
Element childElement = document.createElement("child");
rootElement.appendChild(childElement);
childElement.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:pfx","http://www.example.com");
childElement.setAttribute("answer", "42");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(new DOMSource(document), new StreamResult(System.out));
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stephan Schlecht |
