Copying attributes from one XML element to another with Java



I am writing a Java program that will create an XML file from various pieces of data.


There are attribute strings containing URLs that are reused throughout the XML. I wanted to reuse these attributes (i.e., copy them from one element to another). I currently have something like this:



public class copyAttributes {

public static final String google_url = "http://www.google.com";

DocumentBuilderFactor docFac = DocumentBuilderFactory.newInstance();
DocumentBuilder build = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();

public static Attr googleAttr = doc.createAttribute("ref:GoogleMainSite");
googleAttr.setValue(google_url);

Element rootElement = doc.createElement("Root_Element");
rootElement.setAttributeNode(googleAttr);


...this is fine so far if I don't have any other elements.


Now, I want to have multiple elements containing that same Google URL attribute node. I know that's redundant, but I'm following an XSD that specifically says attributes have to be reused. I know you can't just do this:



Element childElement = doc.createElement("Child_Element");
childElement.setAttributeNode(googleAttr);
rootElement.appendChild(childElement);


...because I know you will get an INUSE_ATTRIBUTE_ERR (I tried, that's how I know). But I want to reuse this attribute, as it will occur many times throughout the XML.


I did find this: sample code for copying attributes from one element to another, but when I included that sample "Utils" class in my package and called it this way:



Utils utils = new Utils();
utils.copyAttributes(rootElement, childElement);


...I receive a "NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces."


There isn't much information out there about this "Namespace_err" message.


The other solution I found is to simply clone an element. But this doesn't solve my problem either, since in some cases I won't want to reuse all of the attributes of another element, I will only want to use a couple of them.


Basically my question is: How do you go about reusing attribute nodes on multiple elements in an XML schema created via a Java program?


No comments:

Post a Comment