2

I need to create an XML document with the following structure:

<?xml version="1.0" ?> 
<Cancelacion xmlns:xsd="http://www.w3.org/2001/XMLSchema"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             RfcEmisor="VSI850514HX4" 
             Fecha="2011-11-23T17:25:06" 
             xmlns="http://cancelacfd.sat.gob.mx">
    <Folios>
        <UUID>BD6CA3B1-E565-4985-88A9-694A6DD48448</UUID> 
    </Folios>
</Cancelacion>

The structure MUST be that way. But I'm not very familiar with the namespace declaration for the XML Elements. I can correctly generate an XML with the following structure:

<?xml version="1.0" ?> 
<Cancelacion RfcEmisor="VSI850514HX4" 
             Fecha="2011-11-23T17:25:06" 
             xmlns="http://cancelacfd.sat.gob.mx">
    <Folios>
        <UUID>BD6CA3B1-E565-4985-88A9-694A6DD48448</UUID> 
    </Folios>
</Cancelacion>


But the problem is that I can't get to include the xmls:xsd and xmlns:xsi correctly. The code for properly generating the previously mentioned code is:

// Crear un document XML vacío
DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
dbfac.setNamespaceAware(true);
DocumentBuilder docBuilder;
docBuilder = dbfac.newDocumentBuilder();
Document doc = docBuilder.newDocument();
doc.setXmlVersion("1.0");
doc.setXmlStandalone(true);

Element cancelacion = doc.createElementNS("http://cancelacfd.sat.gob.mx","Cancelacion");
cancelacion.setAttribute("RfcEmisor", rfc);
cancelacion.setAttribute("Fecha", fecha);
doc.appendChild(cancelacion);

Element folios = doc.createElementNS("http://cancelacfd.sat.gob.mx", "Folios");
cancelacion.appendChild(folios);
for (int i=0; i<uuid.length; i++) {
    Element u = doc.createElementNS("http://cancelacfd.sat.gob.mx","UUID");
    u.setTextContent(uuid[i]);
    folios.appendChild(u);
}

1 Answer 1

6

You can add additional namespaces by calling setAttributeNS method on the root element as shown in below example

// get the root element
Element rootElement = xmlDoc.getDocumentElement();

// add additional namespace to the root element
rootElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsd", "http://www.w3.org/2001/XMLSchema");

You can then add elements to a given namespace by using the method like below

// append author element to the document element
Element author = xmlDoc.createElement("xsd:element");

Read this article for more details.

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.