jesric1029
jesric1029

Reputation: 718

How to make specific header elements appear in Java XML

I have a rather unique problem. I have a tool for work that allows a user create an xml file. I won't get too into the details except to say they use a GUI and JTable to populate the tags that will be put into the XML file, this is all done with DOM Parsing. The XML that is generated has a specific format. Every tag must be in the correct place and the XML must match the schema 100% or it will fail during later testing.

I've had a strange error reported in that files generated with this tool don't correctly match the standard due to the header area of the XML. (Not sure what you call it, I don't think it's the namespace). Anyway, here is how my tool generates that top header:

<Document xmlns="urn:iso:std:iso:20022:tech:xsd:caie.011.011.01>

Apparently the expected result is this:

<Document xmlns="urn:iso:std:iso:20022:tech:xsd:caie.011.011.01" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

I'm not sure what the purpose is of having the URL there to the w3 website but apparently it's needed in processing. Here is how the general structure of my XML code looks:

try{

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        doc.setXmlStandalone(true);

        Element rootElement = doc.createElementNS("urn:iso:std:iso:20022:tech:xsd:caie.011.011.01", "Document");
        doc.appendChild(rootElement);

        Element BkToCstmrDbtCdtNtfctn = doc.createElement("BkToCstmrDbtCdtNtfctn");
        rootElement.appendChild(BkToCstmrDbtCdtNtfctn);

        Element GrpHdr = doc.createElement("GrpHdr");
        BkToCstmrDbtCdtNtfctn.appendChild(GrpHdr);

Upvotes: 0

Views: 164

Answers (1)

Md Ayub Ali Sarker
Md Ayub Ali Sarker

Reputation: 11567

Add "xmlns:xsi" as attribute to rootElement like

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElementNS("urn:iso:std:iso:20022:tech:xsd:caie.011.011.01", "Document");
        rootElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        doc.appendChild(rootElement);

Upvotes: 1

Related Questions